import React, { Component } from "react";
import {
    Layout, Menu, Icon, Table, Divider, Button, Modal, Form, Input,
    TimePicker, Popconfirm, message, Alert, DatePicker, Tree, Steps,
    Select, Tabs, List, Card, Collapse, Dropdown, Drawer, Skeleton,
    Transfer, Tag, Col, Row, Avatar, AutoComplete, notification,
    Progress, Spin, Rate, Upload, Checkbox
} from "antd";
import moment from 'moment';
import RViewerJS from 'viewerjs-react';
import { getPatrolNumRankApi, getBranchCompusApi } from "../js/dailystatistics.js";
import {
    getSchoolLevelByEduIdApi, getSchoolBySchooLevelApi, getAverageInspectClassRatesApi, getSchoolInspectCompositeRankApi, getSchoolInspectCompositeRank2Api,
    getSchoolBySchooLevel2Api, getAverageInspectClassRates2Api, getEduPatrolNumRankApi, getEduPatrolNumRankApi2, getEduPatrolRatesRankApi, getEduPatrolRatesRankApi2,
    getEduPatrolPointsRankApi, getEduPatrolPointsRankApi2, getEduDangerNumRankApi, getEduDangerNumRankApi2, getEduDangerCategoryApi, getEduDangerDealRateApi, getEduDangerDealRateApi2, getComprehensivePointsRankApi, getComprehensivePointsRankApi2, getXunchaPlanApi, deleteXunchaPlanApi, updateXunchaPlanApi, getDingshiPlanApi, updateDingshiPlanApi, getDepartmentParentApi, getAllChildDepartmentApi, addXunchaPlanForDepartmentApi, IsUseForDepartment, addXunchaPlanApi, XunchaRecordSearchApi, DailyRecordSearchApi, getXunchaContentApi, addContentItemApi
} from "../js/edudailystatistics.js";

import { safetysceneDetailByIdApi, getDepartmentApi, getSchoolInfoByNameApi, getXunchaConditionDetail, getXunchaDealDetail, safetysceneBySchoolApi, allInspectItemCategory, getExistCategoryBySchoolIdAip, allUserApi, getSafetySceneSearchApi, getSafetySceneSearchChartDataApi, getDailyConditionDetailApi, getDailyDealDetailApi, getSafetySceneByCategory} from "../js/api.js";
import { UrlPrefix, iconFontUrl, screenUrl } from "../js/config.js";


import * as echarts from 'echarts'
import '../css/bigscreen.css'
import { get } from "jquery";
import { propTypes } from "qrcode.react";
import { exportExcel } from "../js/utils.js";

const FormItem = Form.Item;
const RangePicker = DatePicker.RangePicker;
const { WeekPicker } = DatePicker;
const { TreeNode } = Tree;
const TabPane = Tabs.TabPane;
const IconFont = Icon.createFromIconfontCN({
    scriptUrl: iconFontUrl,
});

const dateFormat = 'YYYY-MM-DD';
const screenath = '/bigscreen/patrol/'

const toSchoolUrl = (record) => {
    let schoolUrl;
    getSchoolInfoByNameApi(record.schoolname)
        .then((res) => {
            if (res.data == '') {
                message.info('暂无进行大屏配置', 1);
            } else {
                schoolUrl = screenUrl + screenath + parseInt(res.data.id) + '/' + 1;
                window.open(schoolUrl);
            }
        })
        .catch((e) => {
            if (e.response) {
                console.info(e.response.data)
                console.info(e.response.status)
                console.info(e.response.headers)
            } else if (e.request) {
                console.info(e.request)
            } else {
                console.info('error', e.message)
            }
            console.info(e.config)
        });
}

//校巡检次数
class inspectNumRank extends Component {
    constructor(props) {
        super(props);
        this.state = {
            alertVisible: false, //提示
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            tableLoading: true,
            filteredInfo: null,
            sortedInfo: null,
            searchData: [],
            schoolLevel: [],
            countyList: [],
            searchChartLoading: true,
            chartSearchData: {},
            chartSearchAvg: "",
            startTime: "",
            endTime: "",
            isSearch: false,
            departmentId: sessionStorage.getItem("departmentId")
        };
    }
    componentWillMount() {
    }
    componentDidMount() {
        this.refreshData();
    }
    getBeforeDayTime() {
        var time = (new Date()).getTime() - 24 * 60 * 60 * 1000;
        var beforeday = new Date(time); // 获取的是前一天日期

        beforeday = beforeday.getFullYear() + "-" + (beforeday.getMonth() + 1 > 9
            ? (beforeday.getMonth() + 1) : "0" + (beforeday.getMonth()+1)) + "-" + (beforeday.getDate() > 9
                ? (beforeday.getDate()) : "0" + (beforeday.getDate())); //字符串拼接转格式：例如2018-08-19
        
        return beforeday
    }
    getBeforeWeekTime() {
        var time = (new Date()).getTime() - 24 * 60 * 60 * 1000 * 7;
        var beforeweek = new Date(time); // 获取的是前一周日期

        beforeweek = beforeweek.getFullYear() + "-" + (beforeweek.getMonth() + 1 > 9
            ? (beforeweek.getMonth() + 1) : "0" + (beforeweek.getMonth() + 1)) + "-" + (beforeweek.getDate() > 9
                ? (beforeweek.getDate()) : "0" + (beforeweek.getDate())); //字符串拼接转格式：例如2018-08-19
        return beforeweek
    }
    formatDate(date) {
        var myyear = date.getFullYear();
        var mymonth = date.getMonth() + 1;
        var myweekday = date.getDate();
        if (mymonth < 10) {
            mymonth = "0" + mymonth;
        }
        if (myweekday < 10) {
            myweekday = "0" + myweekday;
        }
        return (myyear + "-" + mymonth + "-" + myweekday);
    }

    getLastWeekStartDate() {
        var now = new Date(); //当前日期
        var nowDayOfWeek = now.getDay() - 1; //今天本周的第几天
        var nowDay = now.getDate(); //当前日
        var nowMonth = now.getMonth(); //当前月
        var nowYear = now.getYear(); //当前年
        nowYear += (nowYear < 2000) ? 1900 : 0; //
        var lastMonthDate = new Date(); //上月日期
        lastMonthDate.setDate(1);
        lastMonthDate.setMonth(lastMonthDate.getMonth() - 1);
        var lastYear = lastMonthDate.getYear();
        var lastMonth = lastMonthDate.getMonth();
        var weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek - 7);
        return this.formatDate(weekStartDate);
    }

    getLastWeekEndDate() {
        var now = new Date(); //当前日期
        var nowDayOfWeek = now.getDay() - 1; //今天本周的第几天
        var nowDay = now.getDate(); //当前日
        var nowMonth = now.getMonth(); //当前月
        var nowYear = now.getYear(); //当前年
        nowYear += (nowYear < 2000) ? 1900 : 0; //
        var lastMonthDate = new Date(); //上月日期
        lastMonthDate.setDate(1);
        lastMonthDate.setMonth(lastMonthDate.getMonth() - 1);
        var lastYear = lastMonthDate.getYear();
        var lastMonth = lastMonthDate.getMonth();
        var weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek - 1);
        return this.formatDate(weekStartDate);
    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        let columnData = [];
        let schoolLevel;
        // var startTime = this.getBeforeWeekTime()
        // var endTime = this.getBeforeDayTime()
        var startTime = this.getLastWeekStartDate()
        var endTime = this.getLastWeekEndDate()
        //dpartmentId < 0 表全市，如departmentId = -1，默认为全市
        let departmentId = -sessionStorage.getItem("departmentId")
 
        getSchoolBySchooLevelApi(departmentId, schoolLevel, startTime, endTime)
            .then((res) => {
                res.data.forEach((item, index) => {
                    columnData.push({
                        key: index + 1,
                        schoolname: item.schoolname,
                        inspectNum: item.inspectNum,
                        departmentName: item.departmentName
                    });
                });
                this.setState({
                    columnData: columnData,
                    startTime: startTime,
                    endTime: endTime,
                    tableLoading: false,
                    alertVisible: false,
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

            getSchoolBySchooLevel2Api(departmentId, schoolLevel, startTime, endTime)
            .then((res) => {

                console.log("getSchoolBySchooLevel2Api==============", res)

                if (res.data.serialList.length == 0) {
                    this.setState({
                        schoolResult: [],
                        schoolResult2: [],
                        schoolName: [],
                        eduinspectnumavg: 0,
                        eduinspectnumsum: 0,
                        serialList: [],
                        tableLoading: false,
                        isSearch: false
                    });
                } else {
                    this.setState({
                        schoolResult: res.data.schoolResults,
                        schoolResult2: res.data.schoolResults2,
                        schoolName: res.data.schoolNames,
                        eduinspectnumavg: res.data.eduinspectnumavg,
                        eduinspectnumsum: res.data.eduinspectnumsum,
                        serialList: res.data.serialList,
                        searchChartLoading: false,
                        tableLoading: false,
                        alertVisible: false,
                        isSearch: true
                    });
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

        this.getSchoolLevelByEduId(sessionStorage.getItem("departmentId"), 1)
        

        getDepartmentApi(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                this.setState({
                    countyList: res.data
                });
            }).catch((e) => {
                console.log(e);
            })
    }

    searchSubmit = (e) => {
        var schoolLevel;
        var departmentId;
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            console.log("values==============", values);

            if (values.deadline == undefined && values.schoolLevel == undefined) {
                message.error('请至少填写一项条件再进行搜索');
            } else {
                if (values.schoolLevel != undefined) {
                    schoolLevel = values.schoolLevel
                }
                if(!isNaN(values.county)){
                    departmentId = values.county
                }else{
                    departmentId = -parseInt(sessionStorage.getItem("departmentId"))
                }
                
                this.setState({
                    tableLoading: true
                });
                let columnData = [];

                getSchoolBySchooLevelApi(departmentId, schoolLevel, this.state.startTime, this.state.endTime)
                    .then((res) => {
                        res.data.forEach((item, index) => {
                            columnData.push({
                                key: index + 1,
                                schoolname: item.schoolname,
                                inspectNum: item.inspectNum,
                                departmentName: item.departmentName
                            });
                        });
                        this.setState({
                            columnData: columnData,
                            tableLoading: false,
                            alertVisible: false,
                        });
                        if(values.average == 1){
                            let columnDataAvg = [];
                            let columnDataTemp = this.state.columnData;
                            let sum = 0;
                            for(let i = 0;i < columnDataTemp.length; i++){
                                sum += columnDataTemp[i].inspectNum;
                            }
                            let avg = sum / columnDataTemp.length;
                            console.log(avg)
                            let index = 1;
                            for(let i = 0;i < columnDataTemp.length;i ++){
                                if(columnDataTemp[i].inspectNum <= avg){
                                    columnDataTemp[i].key = index++;
                                    columnDataAvg.push(columnDataTemp[i]);
                                }
                            }
                            this.setState({
                                columnData: columnDataAvg
                            })
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });

                getSchoolBySchooLevel2Api(departmentId, schoolLevel, this.state.startTime, this.state.endTime)
                    .then((res) => {
                        if (res.data.serialList.length == 0) {
                            this.setState({
                                schoolResult: [],
                                schoolResult2: [],
                                schoolName: [],
                                eduinspectnumavg: 0,
                                eduinspectnumsum: 0,
                                serialList: [],
                                tableLoading: false,
                                isSearch: false
                            });
                        } else {
                            this.setState({
                                schoolResult: res.data.schoolResults,
                                schoolResult2: res.data.schoolResults2,
                                schoolName: res.data.schoolNames,
                                eduinspectnumavg: res.data.eduinspectnumavg,
                                eduinspectnumsum: res.data.eduinspectnumsum,
                                serialList: res.data.serialList,
                                searchChartLoading: false,
                                tableLoading: false,
                                alertVisible: false,
                                isSearch: true
                            });
                            if(values.average == 1){
                                let schoolResultAvg = [];
                                let schoolResult2Avg = [];
                                let schoolNameAvg = [];
                                let serialListAvg = [];
                                let t1 = [];
                                let t2 = [];
                                let t3 = [];
                                let count = 0;
                                for(let i = 0;i < this.state.schoolResult.length;i++){
                                    for(let j = 0;j < this.state.schoolResult[i].length;j++){
                                        if(this.state.schoolResult[i][j] <= parseInt(this.state.eduinspectnumavg)){
                                            if(count != 0 && count % 5 == 0){
                                                schoolResultAvg.push(t1);
                                                schoolResult2Avg.push(t2);
                                                schoolNameAvg.push(t3);
                                                serialListAvg.push(parseInt((count-1) / 5) + 1);
                                                t1 = [];
                                                t2 = [];
                                                t3 = [];
                                            }
                                            t1.push(this.state.schoolResult[i][j]);
                                            t2.push(this.state.schoolResult2[i][j]);
                                            t3.push(this.state.schoolName[i][j]);
                                            count++;
                                        }
                                    }
                                }
                                if(t1.length != 0){
                                    schoolResultAvg.push(t1);
                                    schoolResult2Avg.push(t2);
                                    schoolNameAvg.push(t3);
                                    serialListAvg.push(parseInt((count-1) / 5) + 1);
                                }
                                this.setState({
                                    schoolResult: schoolResultAvg,
                                    schoolResult2: schoolResult2Avg,
                                    schoolName: schoolNameAvg,
                                    serialList: serialListAvg,
                                })
                            }
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });

            }
        });
    }
    clearAll = () => {
        this.setState({
            filteredInfo: null,
            sortedInfo: null,
        });
    }
    handleChange = (pagination, filters, sorter) => {
        this.setState({
            filteredInfo: filters,
            sortedInfo: sorter,
        });
    }
    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
    }
    handleSearchReset = clearFilters => () => {
        clearFilters();
    }
    onRef = (ref) => {
        this.child = ref
    }

    searchReset = () => {
        this.props.form.resetFields();
    }

    setFullScreen(opts) {
        this.setState({
            fullScreenVisible: true,
        })
        let fullchart = echarts.init(document.getElementById('fullScreen'))
        fullchart.setOption(opts);
    }

    fullScreenCancel() {
        this.setState({
            fullScreenVisible: false,
        })
    }
    handleSelectTime = (value, dateString) => {
        if (dateString[0] != '' && dateString[1] != '') {
            this.setState({
                startTime: dateString[0],
                endTime: dateString[1],
            })
        }

    }
    handleSelectTime1 = (date, dateString) => {
        console.log(date, dateString)
        const startDate = moment(date).isoWeekday(1).format('YYYY-MM-DD'); //周一日期
        // console.log("周一=====", startDate)
        if (dateString != '') {
            this.setState({
                startTime: startDate,
            })
        }
    }

    handleSelectTime2 = (date, dateString) => {
        // console.log(date, dateString)
        const endDate = moment(date).isoWeekday(7).format('YYYY-MM-DD'); //周日日期
        console.log("周日======", endDate)
        if (dateString != '') {
            this.setState({
                endTime: endDate,
            })
        }
    }

    handleChange2() {
        console.log("handleChange2()=========================")
    }

    getSchoolLevelByEduId(id, allType){
        getSchoolLevelByEduIdApi(id, allType)
            .then((res) => {
                this.setState({
                    schoolLevel: res.data,
                });

            })
    }
    

    render() {
        let schoolLevelOptions = [];
        schoolLevelOptions.push(<Option value={null} key={-1}>全部</Option>)
        if (this.state.schoolLevel.length != 0) {
            schoolLevelOptions.push(this.state.schoolLevel.map((d, index) =>
                <Option value={d.schoolLevel} key={index}>{d.schoolLevel}</Option>
            ))
        }
        let countyOptions = [];
        let name = sessionStorage.getItem("departmentName")
        let id = parseInt(sessionStorage.getItem("departmentId"))
        countyOptions.push(<Option value={-id} key={-id}>{name.substring(0, name.indexOf("市"))}全市</Option>)
        if(this.state.countyList.length != 0){
            countyOptions.push(this.state.countyList.map((item) =>
                <Option value={item.id} key={item.id}>{item.name}</Option>
            ))
        }

        const { getFieldDecorator, getFieldValue } = this.props.form;
        let { sortedInfo, filteredInfo } = this.state;
        sortedInfo = sortedInfo || {};
        filteredInfo = filteredInfo || {};
        const columnsSearch = [{
            title: "序号",
            dataIndex: "key",
            key: "key"
        }, {
            title: "学校",
            dataIndex: "schoolname",
            key: "schoolname",
            filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                <div className="custom-filter-dropdown">
                    <Input
                        ref={ele => this.searchInput = ele}
                        value={selectedKeys[0]}
                        onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                        onPressEnter={this.handleSearch(selectedKeys, confirm)}
                    />
                    <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                    <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                </div>
            ),
            filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
            onFilter: (value, record) => record.schoolname.toLowerCase().includes(value.toLowerCase()),
            onFilterDropdownVisibleChange: (visible) => {
                if (visible) {
                    setTimeout(() => {
                        this.searchInput.focus();
                    });
                }
            }
        }, 
        sessionStorage.getItem("departmentType") == "教育局" ? 
        {
            title: "区县",
            dataIndex: "departmentName",
            key: "departmentName"
        }:{}, {
            title: "巡检次数",
            dataIndex: "inspectNum",
            key: "inspectNum",
            sorter: (a, b) => a.inspectNum - b.inspectNum,
            sortDirections: ['descend', 'ascend'],

        },
        {
            title: '详情',
            dataIndex: 'action',
            key: 'action',
            render: (text, record) => {
                //  console.log("============================", record)
                return (
                    <span>
                        <a
                            onClick={toSchoolUrl.bind(this, record)}
                            // href={this.stahoolUrl}   
                            target="_blank"
                        >
                            查看详情
                        </a>
                        {/* <Button onClick={this.toSchoolUrl.bind(this, record)}> 查看详情</Button> */}
                    </span>
                )
            }
        }]
        let labelCol = {
            sm: { span: 6 },
            xl: { span: 6 },
            xxl: { span: 5 },
        };

        let wrapperCol = {
            sm: { span: 18 },
            xl: { span: 18 },
            xxl: { span: 19 },
        };

        // Excel头部标题
        const header = [
            {
                title: '序号',
                dataIndex: 'key',
                key: 'key',
            }, {
                title: '学校',
                dataIndex: 'schoolname',
                key: 'schoolname',
            }, {
                title: '区县',
                dataIndex: 'departmentName',
                key: 'departmentName',
            }, {
                title: '巡检次数(次)',
                dataIndex: 'inspectNum',
                key: 'inspectNum',
            }
        ]



        return (
            <div style={{ marginBottom: 16 }}>
                <Form style={{
                    padding: '12px',
                    backgroundColor: '#fafafa',
                    borderRadius: 8,
                    marginBottom: 16,
                }}
                    layout="inline"
                    onSubmit={this.searchSubmit}>
                    <Row>
                        <Col span={8}>
                            <FormItem
                                label="截止日期"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("deadline", {
                                    rules: [{
                                        type: 'array',
                                        required: false,
                                    }],
                                    initialValue: [ // 核心代码
                                        moment(this.getBeforeWeekTime(), dateFormat),
                                        moment(this.getBeforeDayTime(), dateFormat),
                                      ],
                          
                                })(
                                    // <RangePicker
                                    //     style={{ width: '100%' }}
                                    //     format={dateFormat}
                                    //     onChange={this.handleSelectTime} />
                                    <div>
                                        <WeekPicker style={{ width: '48%' }} picker="week" defaultValue={moment(this.getBeforeWeekTime(), dateFormat)} placeholder="请选择开始日期" onChange={this.handleSelectTime1} />~
                                         <WeekPicker style={{ width: '48%' }} picker="week" defaultValue={moment(this.getBeforeWeekTime(), dateFormat)} placeholder="请选择结束日期" onChange={this.handleSelectTime2} />
                                    </div>
                                )}
                            </FormItem>
                        </Col>                
                        <Col span={8}>
                            <FormItem
                                label="学校类型"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("schoolLevel", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请选择学校类型">
                                        {schoolLevelOptions}
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8}>
                        <FormItem
                                label="数值"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("average", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请选择数值情况">
                                        <Option value={0} key={0}>所有</Option>
                                        <Option value={1} key={1}>低于平均值</Option>
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        <Col>
                            <FormItem
                                style={{ float: 'right' }}>
                                <Button type="primary" htmlType="submit">搜索</Button>
                                <Button style={{ marginLeft: 8 }} onClick={this.searchReset}>清空</Button>
                                <Button type="primary" style={{ marginLeft: 8 }} onClick={() =>  {
                                    exportExcel(header, this.state.columnData, "学校巡检次数排名.xlsx")
                                    }}>导出Excel
                                </Button>  
                            </FormItem>
                        </Col>
                        {sessionStorage.getItem("departmentType") == "教育局" ? (
                            <Col span={8}>
                            <FormItem
                                label="区县"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("county", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请选择区县"
                                        onSelect = {(e) => {
                                            if(e < 0){
                                                this.getSchoolLevelByEduId(parseInt(sessionStorage.getItem("departmentId")), 1)
                                            }else {
                                                this.getSchoolLevelByEduId(e, 0)
                                            }
                                        }}>
                                        {countyOptions}
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        )
                        :null
                        }
                    </Row>
                </Form>
                <div>
                    {
                        this.state.isSearch ?
                            (
                                <div style={{
                                    marginBottom: 16,
                                    padding: 16,
                                    width: '100%',
                                    height: 350,
                                    border: '1px solid',
                                    borderColor: '#f5f5f5'
                                }}>
                                    <Skeleton loading={this.state.searchChartLoading} active>
                                        <ChartSearch
                                            that={this}
                                            schoolName={this.state.schoolName}
                                            schoolResult={this.state.schoolResult}
                                            schoolResult2={this.state.schoolResult2}
                                            serialList={this.state.serialList}
                                            eduinspectnumavg={this.state.eduinspectnumavg}
                                            eduinspectnumsum={this.state.eduinspectnumsum}
                                            divId={'chartSearch'} />
                                    </Skeleton>
                                </div>
                            ) : null
                    }
                    <Table
                        dataSource={this.state.columnData}
                        columns={columnsSearch}
                        loading={this.state.tableLoading}
                        locale={{ emptyText: '暂无数据' }}
                        onChange={this.handleChange2}
                        rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                        pagination={{  //分页
                            total: this.state.searchData.length, //数据总数量
                            defaultPageSize: 10, //默认显示几条一页
                            //pageSize: 10,
                            showTotal: function (total) {  //设置显示一共几条数据
                                return '共 ' + total + ' 条数据';
                            },
                            showSizeChanger: true,
                            showQuickJumper: true,
                            pageSizeOptions: [5, 10, 20, 30]
                        }} />
                </div>
            </div>
        );
    }
}

const EduInspectNum = Form.create()(inspectNumRank);


class eduInspectFinishedRate extends Component {
    constructor(props) {
        super(props);
        this.state = {
            alertVisible: false, //提示
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            tableLoading: true,
            filteredInfo: null,
            sortedInfo: null,
            searchData: [],
            branchCampus: [],
            countyList: [],
            searchChartLoading: true,
            chartSearchData: {},
            startTime: "",
            endTime: "",
            isSearch: false,
            departmentId: sessionStorage.getItem("departmentId")
        };
    }
    
    componentWillMount() {
    }
    componentDidMount() {
        this.refreshData();
    }
    getBeforeDayTime() {
        var time = (new Date()).getTime() - 24 * 60 * 60 * 1000;
        var beforeday = new Date(time); // 获取的是前一天日期

        beforeday = beforeday.getFullYear() + "-" + (beforeday.getMonth() + 1 > 9
            ? (beforeday.getMonth() + 1) : "0" + (beforeday.getMonth()+1)) + "-" + (beforeday.getDate() > 9
                ? (beforeday.getDate()) : "0" + (beforeday.getDate())); //字符串拼接转格式：例如2018-08-19
        
        return beforeday
    }
    getBeforeWeekTime() {
        var time = (new Date()).getTime() - 24 * 60 * 60 * 1000 * 7;
        var beforeweek = new Date(time); // 获取的是前一周日期

        beforeweek = beforeweek.getFullYear() + "-" + (beforeweek.getMonth() + 1 > 9
            ? (beforeweek.getMonth() + 1) : "0" + (beforeweek.getMonth() + 1)) + "-" + (beforeweek.getDate() > 9
                ? (beforeweek.getDate()) : "0" + (beforeweek.getDate())); //字符串拼接转格式：例如2018-08-19
        return beforeweek
    }

    formatDate(date) {
        var myyear = date.getFullYear();
        var mymonth = date.getMonth() + 1;
        var myweekday = date.getDate();
        if (mymonth < 10) {
            mymonth = "0" + mymonth;
        }
        if (myweekday < 10) {
            myweekday = "0" + myweekday;
        }
        return (myyear + "-" + mymonth + "-" + myweekday);
    }

    getLastWeekStartDate() {
        var now = new Date(); //当前日期
        var nowDayOfWeek = now.getDay() - 1; //今天本周的第几天
        var nowDay = now.getDate(); //当前日
        var nowMonth = now.getMonth(); //当前月
        var nowYear = now.getYear(); //当前年
        nowYear += (nowYear < 2000) ? 1900 : 0; //
        var lastMonthDate = new Date(); //上月日期
        lastMonthDate.setDate(1);
        lastMonthDate.setMonth(lastMonthDate.getMonth() - 1);
        var lastYear = lastMonthDate.getYear();
        var lastMonth = lastMonthDate.getMonth();
        var weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek - 7);
        return this.formatDate(weekStartDate);
    }

    getLastWeekEndDate() {
        var now = new Date(); //当前日期
        var nowDayOfWeek = now.getDay() - 1; //今天本周的第几天
        var nowDay = now.getDate(); //当前日
        var nowMonth = now.getMonth(); //当前月
        var nowYear = now.getYear(); //当前年
        nowYear += (nowYear < 2000) ? 1900 : 0; //
        var lastMonthDate = new Date(); //上月日期
        lastMonthDate.setDate(1);
        lastMonthDate.setMonth(lastMonthDate.getMonth() - 1);
        var lastYear = lastMonthDate.getYear();
        var lastMonth = lastMonthDate.getMonth();
        var weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek - 1);
        return this.formatDate(weekStartDate);
    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        let columnData = [];
        let schoolLevel;
        // var startTime = this.getBeforeWeekTime()
        // var endTime = this.getBeforeDayTime()
        var startTime = this.getLastWeekStartDate()
        var endTime = this.getLastWeekEndDate()
        let departmentId = -sessionStorage.getItem("departmentId")

        getAverageInspectClassRatesApi(departmentId, schoolLevel, startTime, endTime)
            .then((res) => {
                res.data.forEach((item, index) => {
                    columnData.push({
                        key: index + 1,
                        schoolname: item.schoolname,
                        inspectclassrates: item.inspectclassrates,
                        departmentName: item.departmentName
                    });
                });
                this.setState({
                    columnData: columnData,
                    tableLoading: false,
                    alertVisible: false,
                    startTime:startTime,
                    endTime:endTime
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

            getAverageInspectClassRates2Api(departmentId, schoolLevel, startTime, endTime)
            .then((res) => {
                if (res.data.serialList.length == 0) {
                    this.setState({
                        schoolResult: [],
                        schoolName: [],
                        serialList: [],
                        eduinspectRatesavg: [],
                        tableLoading: false,
                        isSearch: false
                    });
                } else {
                    this.setState({
                        schoolResult: res.data.schoolResults,
                        schoolName: res.data.schoolNames,
                        serialList: res.data.serialList,
                        eduinspectRatesavg: res.data.eduinspectRatesavg,
                        searchChartLoading: false,
                        tableLoading: false,
                        alertVisible: false,
                        isSearch: true
                    });
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

        
        this.getSchoolLevelByEduId(sessionStorage.getItem("departmentId"), 1)
        

        getDepartmentApi(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                this.setState({
                    countyList: res.data
                });
            }).catch((e) => {
                console.log(e);
            })
    }

    searchSubmit = (e) => {
        var schoolLevel;
        var departmentId;
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            console.log("values==============", values);

            if (values.deadline == undefined && values.schoolLevel == undefined) {
                message.error('请至少填写一项条件再进行搜索');
            } else {
                if (values.schoolLevel != undefined) {
                    schoolLevel = values.schoolLevel
                }

                if(!isNaN(values.county)){
                    departmentId = values.county
                }else{
                    departmentId = -parseInt(sessionStorage.getItem("departmentId"))
                }
                this.setState({
                    tableLoading: true
                });
                let columnData = [];
                getAverageInspectClassRatesApi(departmentId, schoolLevel, this.state.startTime, this.state.endTime)
                    .then((res) => {
                        if (res.data.length == 0) {
                            this.setState({
                                columnData: [],
                                chartSearchData: [],
                                tableLoading: false,
                                isSearch: false
                            });
                        } else {
                            let chartSearchData = {
                                key: [],
                                value: [],
                            };
                            res.data.forEach((item, index) => {
                                columnData.push({
                                    key: index + 1,
                                    schoolname: item.schoolname,
                                    inspectclassrates: item.inspectclassrates,
                                    departmentName: item.departmentName
                                });
                                chartSearchData.key.push(item.schoolname);
                                chartSearchData.value.push(item.inspectclassrates);
                            });
                            this.setState({
                                columnData: columnData,
                                searchChartLoading: false,
                                chartSearchData: chartSearchData,
                                tableLoading: false,
                                alertVisible: false,
                                isSearch: true
                            });
                            if(values.average == 1){
                                let columnDataAvg = [];
                                let columnDataTemp = this.state.columnData;
                                let sum = 0;
                                for(let i = 0;i < columnDataTemp.length; i++){
                                    sum += parseFloat(columnDataTemp[i].inspectclassrates);
                                }
                                let avg = sum / columnDataTemp.length;
                                let index = 1;
                                for(let i = 0;i < columnDataTemp.length;i ++){
                                    if(parseFloat(columnDataTemp[i].inspectclassrates) <= avg){
                                        columnDataTemp[i].key = index++;
                                        columnDataAvg.push(columnDataTemp[i]);
                                    }
                                }
                                this.setState({
                                    columnData: columnDataAvg
                                })
                            }
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });

                getAverageInspectClassRates2Api(departmentId, schoolLevel, this.state.startTime, this.state.endTime)
                    .then((res) => {
                        if (res.data.serialList.length == 0) {
                            this.setState({
                                schoolResult: [],
                                schoolName: [],
                                serialList: [],
                                eduinspectRatesavg: [],
                                tableLoading: false,
                                isSearch: false
                            });
                        } else {
                            this.setState({
                                schoolResult: res.data.schoolResults,
                                schoolName: res.data.schoolNames,
                                serialList: res.data.serialList,
                                eduinspectRatesavg: res.data.eduinspectRatesavg,
                                searchChartLoading: false,
                                tableLoading: false,
                                alertVisible: false,
                                isSearch: true
                            });
                            if(values.average == 1){
                                let schoolResultAvg = [];
                                let schoolNameAvg = [];
                                let serialListAvg = [];
                                let t1 = [];
                                let t3 = [];
                                let count = 0;
                                for(let i = 0;i < this.state.schoolResult.length;i++){
                                    for(let j = 0;j < this.state.schoolResult[i].length;j++){
                                        if(parseFloat(this.state.schoolResult[i][j]) <= parseFloat(this.state.eduinspectRatesavg)){
                                            if(count != 0 && count % 5 == 0){
                                                schoolResultAvg.push(t1);
                                                schoolNameAvg.push(t3);
                                                serialListAvg.push(parseInt((count-1) / 5) + 1);
                                                t1 = [];
                                                t3 = [];
                                            }
                                            t1.push(this.state.schoolResult[i][j]);
                                            t3.push(this.state.schoolName[i][j]);
                                            count++;
                                        }
                                    }
                                }
                                if(t1.length != 0){
                                    schoolResultAvg.push(t1);
                                    schoolNameAvg.push(t3);
                                    serialListAvg.push(parseInt((count-1) / 5) + 1);
                                }
                                this.setState({
                                    schoolResult: schoolResultAvg,
                                    schoolName: schoolNameAvg,
                                    serialList: serialListAvg,
                                })
                            }
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });


            }
        });
    }
    clearAll = () => {
        this.setState({
            filteredInfo: null,
            sortedInfo: null,
        });
    }
    handleChange = (pagination, filters, sorter) => {
        this.setState({
            filteredInfo: filters,
            sortedInfo: sorter,
        });
    }
    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
    }
    handleSearchReset = clearFilters => () => {
        clearFilters();
    }
    onRef = (ref) => {
        this.child = ref
    }

    searchReset = () => {
        this.props.form.resetFields();
        // this.setState({
        //     isSearch: false,
        // })
    }

    setFullScreen(opts) {
        this.setState({
            fullScreenVisible: true,
        })
        let fullchart = echarts.init(document.getElementById('fullScreen'))
        fullchart.setOption(opts);
    }

    fullScreenCancel() {
        this.setState({
            fullScreenVisible: false,
        })
    }
    handleSelectTime = (value, dateString) => {
        if (dateString[0] != '' && dateString[1] != '') {
            this.setState({
                startTime: dateString[0],
                endTime: dateString[1],
            })
        }

    }

    handleSelectTime1 = (date, dateString) => {
        console.log(date, dateString)
        const startDate = moment(date).isoWeekday(1).format('YYYY-MM-DD'); //周一日期
        // console.log("周一=====", startDate)
        if (dateString != '') {
            this.setState({
                startTime: startDate,
            })
        }
    }

    handleSelectTime2 = (date, dateString) => {
        console.log(date, dateString)
        const endDate = moment(date).isoWeekday(7).format('YYYY-MM-DD'); //周日日期
        // console.log("周日======", endDate)
        if (dateString != '') {
            this.setState({
                endTime: endDate,
            })
        }
    }

    getSchoolLevelByEduId(id, allType){
        getSchoolLevelByEduIdApi(id, allType)
            .then((res) => {
                this.setState({
                    branchCampus: res.data,
                });

            })
    }

    render() {
        let branchCampusOptions = [];
        branchCampusOptions.push(<Option value={null} key={-1}>全部</Option>)
        if (this.state.branchCampus.length != 0) {
            branchCampusOptions.push(this.state.branchCampus.map((d, index) =>
                <Option value={d.schoolLevel} key={index}>{d.schoolLevel}</Option>
            ))
        }
        let countyOptions = [];
        let name = sessionStorage.getItem("departmentName")
        let id = parseInt(sessionStorage.getItem("departmentId"))
        countyOptions.push(<Option value={-id} key={-id}>{name.substring(0, name.indexOf("市"))}全市</Option>)
        if(this.state.countyList.length != 0){
            countyOptions.push(this.state.countyList.map((item) =>
                <Option value={item.id} key={item.id}>{item.name}</Option>
            ))
        }
        const { getFieldDecorator, getFieldValue } = this.props.form;
        let { sortedInfo, filteredInfo } = this.state;
        sortedInfo = sortedInfo || {};
        filteredInfo = filteredInfo || {};
        const columnsSearch = [{
            title: "序号",
            dataIndex: "key",
            key: "key"
        }, {
            title: "学校",
            dataIndex: "schoolname",
            key: "schoolname",
            filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                <div className="custom-filter-dropdown">
                    <Input
                        ref={ele => this.searchInput = ele}
                        value={selectedKeys[0]}
                        onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                        onPressEnter={this.handleSearch(selectedKeys, confirm)}
                    />
                    <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                    <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                </div>
            ),
            filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
            onFilter: (value, record) => record.schoolname.toLowerCase().includes(value.toLowerCase()),
            onFilterDropdownVisibleChange: (visible) => {
                if (visible) {
                    setTimeout(() => {
                        this.searchInput.focus();
                    });
                }
            }
        }, 
        sessionStorage.getItem("departmentType") == "教育局" ? 
        {
            title: "区县",
            dataIndex: "departmentName",
            key: "departmentName"
        }:{}, {
            title: "巡检完成率(%)",
            dataIndex: "inspectclassrates",
            key: "inspectclassrates",
            sorter: (a, b) => a.inspectclassrates - b.inspectclassrates,
            sortDirections: ['descend', 'ascend'],
        },
        {
            title: '详情',
            dataIndex: 'action',
            key: 'action',
            render: (text, record) => {
                //  console.log("============================", record)
                return (
                    <span>
                        <a
                            onClick={toSchoolUrl.bind(this, record)}
                            // href={this.stahoolUrl}   
                            target="_blank"
                        >
                            查看详情
                        </a>
                        {/* <Button onClick={this.toSchoolUrl.bind(this, record)}> 查看详情</Button> */}
                    </span>
                )
            }
        }]
        let labelCol = {
            sm: { span: 6 },
            xl: { span: 6 },
            xxl: { span: 5 },
        };

        let wrapperCol = {
            sm: { span: 18 },
            xl: { span: 18 },
            xxl: { span: 19 },
        };

        // Excel头部标题
        const header = [
            {
                title: '序号',
                dataIndex: 'key',
                key: 'key',
            }, {
                title: '学校',
                dataIndex: 'schoolname',
                key: 'schoolname',
            }, {
                title: '区县',
                dataIndex: 'departmentName',
                key: 'departmentName',
            }, {
                title: '巡检完成率(%)',
                dataIndex: 'inspectclassrates',
                key: 'inspectclassrates',
            }
        ]


        return (
            <div style={{ marginBottom: 16 }}>
                <Form style={{
                    padding: '12px',
                    backgroundColor: '#fafafa',
                    borderRadius: 8,
                    marginBottom: 16,
                }}
                    layout="inline"
                    onSubmit={this.searchSubmit}>
                    <Row>
                        <Col span={8}>
                            <FormItem
                                label="截止日期"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("deadline", {
                                    rules: [{
                                        type: 'array',
                                        required: false,
                                    }],
                                    initialValue: [ // 核心代码
                                        moment(this.getBeforeWeekTime(), dateFormat),
                                        moment(this.getBeforeDayTime(), dateFormat),
                                      ],
                                })(
                                    // <RangePicker
                                    //     style={{ width: '100%' }}
                                    //     format="YYYY-MM-DD"
                                    //     onChange={this.handleSelectTime} />
                                    <div>
                                        <WeekPicker picker="week" style={{ width: '48%' }} defaultValue={moment(this.getBeforeWeekTime(), dateFormat)} placeholder="请选择开始日期" onChange={this.handleSelectTime1} />~
                                         <WeekPicker picker="week" style={{ width: '48%' }} defaultValue={moment(this.getBeforeWeekTime(), dateFormat)} placeholder="请选择结束日期" onChange={this.handleSelectTime2} />
                                    </div>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8}>
                            <FormItem
                                label="学校类型"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("schoolLevel", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请选择学校类型">
                                        {branchCampusOptions}
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8}>
                        <FormItem
                                label="数值"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("average", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请选择数值情况">
                                        <Option value={0} key={0}>所有</Option>
                                        <Option value={1} key={1}>低于平均值</Option>
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        {sessionStorage.getItem("departmentType") == "教育局" ? (
                            <Col span={8}>
                            <FormItem
                                label="区县"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("county", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请选择区县"
                                        onSelect = {(e) => {
                                            if(e < 0){
                                                this.getSchoolLevelByEduId(parseInt(sessionStorage.getItem("departmentId")), 1)
                                            }else {
                                                this.getSchoolLevelByEduId(e, 0)
                                            }
                                        }}>
                                        {countyOptions}
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        )
                        :null
                        }
                        <Col>
                            <FormItem
                                style={{ float: 'right' }}>
                                <Button type="primary" htmlType="submit">搜索</Button>
                                <Button style={{ marginLeft: 8 }} onClick={this.searchReset}>清空</Button>
                                <Button type="primary" style={{ marginLeft: 8 }} onClick={() =>  {
                                    exportExcel(header, this.state.columnData, "学校巡检完成率排名.xlsx")
                                    }}>导出Excel
                                </Button>  
                            </FormItem>
                        </Col>
                    </Row>
                </Form>
                <div>
                    {
                        this.state.isSearch ?
                            (
                                <div style={{
                                    marginBottom: 16,
                                    padding: 16,
                                    width: '100%',
                                    height: 350,
                                    border: '1px solid',
                                    borderColor: '#f5f5f5'
                                }}>
                                    <Skeleton loading={this.state.searchChartLoading} active>
                                        <ChartSearchEduInspectFinishedRate
                                            that={this}
                                            schoolName={this.state.schoolName}
                                            schoolResult={this.state.schoolResult}
                                            serialList={this.state.serialList}
                                            eduinspectRatesavg={this.state.eduinspectRatesavg}
                                            divId={'chartSearchEduInspectFinishedRate'} />
                                    </Skeleton>
                                </div>
                            ) : null
                    }
                    {
                        this.state.isSearch ? 
                        (
                            <Alert
                            message="学校巡检完成率说明"
                            description={"学校巡检完成率=在统计时间范围内，该学校实际完成巡检项目次数/计划完成巡检项目次数"}
                            type="info"
                            showIcon/>
                        ) : null
                    }
                    <Table
                        dataSource={this.state.columnData}
                        columns={columnsSearch}
                        loading={this.state.tableLoading}
                        locale={{ emptyText: '暂无数据' }}
                        onChange={this.handleChange2}
                        rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                        pagination={{  //分页
                            total: this.state.searchData.length, //数据总数量
                            defaultPageSize: 10, //默认显示几条一页
                            //pageSize: 10,
                            showTotal: function (total) {  //设置显示一共几条数据
                                return '共 ' + total + ' 条数据';
                            },
                            showSizeChanger: true,
                            showQuickJumper: true,
                            pageSizeOptions: [5, 10, 20, 30]
                        }} />
                </div>
            </div>
        );
    }
}

const EduInspectFinishedRate = Form.create()(eduInspectFinishedRate);


class eduInspectComposite extends Component {
    constructor(props) {
        super(props);
        this.state = {
            alertVisible: false, //提示
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            tableLoading: true,
            filteredInfo: null,
            sortedInfo: null,
            searchData: [],
            countyList: [],
            branchCampus: [],
            searchChartLoading: true,
            chartSearchData: {},
            startTime: "",
            endTime: "",
            isSearch: false,
            departmentId: sessionStorage.getItem("departmentId"),
            schoolName: [],
            schoolResult: [],
            serialList: [],
            eduinspectPointsavg: ""
        };
    }
    componentWillMount() {
    }
    componentDidMount() {
        this.refreshData();
    }
    getBeforeDayTime() {
        var time = (new Date()).getTime() - 24 * 60 * 60 * 1000;
        var beforeday = new Date(time); // 获取的是前一天日期

        beforeday = beforeday.getFullYear() + "-" + (beforeday.getMonth() + 1 > 9
            ? (beforeday.getMonth() + 1) : "0" + (beforeday.getMonth()+1)) + "-" + (beforeday.getDate() > 9
                ? (beforeday.getDate()) : "0" + (beforeday.getDate())); //字符串拼接转格式：例如2018-08-19
        
        return beforeday
    }
    getBeforeWeekTime() {
        var time = (new Date()).getTime() - 24 * 60 * 60 * 1000 * 7;
        var beforeweek = new Date(time); // 获取的是前一周日期

        beforeweek = beforeweek.getFullYear() + "-" + (beforeweek.getMonth() + 1 > 9
            ? (beforeweek.getMonth() + 1) : "0" + (beforeweek.getMonth() + 1)) + "-" + (beforeweek.getDate() > 9
                ? (beforeweek.getDate()) : "0" + (beforeweek.getDate())); //字符串拼接转格式：例如2018-08-19
        return beforeweek
    }
    formatDate(date) {
        var myyear = date.getFullYear();
        var mymonth = date.getMonth() + 1;
        var myweekday = date.getDate();
        if (mymonth < 10) {
            mymonth = "0" + mymonth;
        }
        if (myweekday < 10) {
            myweekday = "0" + myweekday;
        }
        return (myyear + "-" + mymonth + "-" + myweekday);
    }

    getLastWeekStartDate() {
        var now = new Date(); //当前日期
        var nowDayOfWeek = now.getDay() - 1; //今天本周的第几天
        var nowDay = now.getDate(); //当前日
        var nowMonth = now.getMonth(); //当前月
        var nowYear = now.getYear(); //当前年
        nowYear += (nowYear < 2000) ? 1900 : 0; //
        var lastMonthDate = new Date(); //上月日期
        lastMonthDate.setDate(1);
        lastMonthDate.setMonth(lastMonthDate.getMonth() - 1);
        var lastYear = lastMonthDate.getYear();
        var lastMonth = lastMonthDate.getMonth();
        var weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek - 7);
        return this.formatDate(weekStartDate);
    }

    getLastWeekEndDate() {
        var now = new Date(); //当前日期
        var nowDayOfWeek = now.getDay() - 1; //今天本周的第几天
        var nowDay = now.getDate(); //当前日
        var nowMonth = now.getMonth(); //当前月
        var nowYear = now.getYear(); //当前年
        nowYear += (nowYear < 2000) ? 1900 : 0; //
        var lastMonthDate = new Date(); //上月日期
        lastMonthDate.setDate(1);
        lastMonthDate.setMonth(lastMonthDate.getMonth() - 1);
        var lastYear = lastMonthDate.getYear();
        var lastMonth = lastMonthDate.getMonth();
        var weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek - 1);
        return this.formatDate(weekStartDate);
    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        let columnData = [];
        let schoolLevel;
        // var startTime = this.getBeforeWeekTime()
        // var endTime = this.getBeforeDayTime()
        var startTime = this.getLastWeekStartDate()
        var endTime = this.getLastWeekEndDate()

        let departmentId = -sessionStorage.getItem("departmentId")

        getSchoolInspectCompositeRankApi(departmentId, schoolLevel, startTime, endTime)
            .then((res) => {
                res.data.forEach((item, index) => {
                    columnData.push({
                        key: index + 1,
                        schoolname: item.schoolname,
                        schoolInspectCompositePoints: item.schoolInspectCompositePoints,
                        departmentName: item.departmentName,
                        inspectnum: item.inspectnum,
                        inspectnofinishednum: item.inspectnofinishednum
                    });
                });
                this.setState({
                    columnData: columnData,
                    tableLoading: false,
                    alertVisible: false,
                    startTime:startTime,
                    endTime:endTime
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
        




        getSchoolInspectCompositeRank2Api(departmentId, schoolLevel, startTime, endTime)
            .then((res) => {
                this.setState({
                    schoolResult: res.data.schoolResults,
                    schoolName: res.data.schoolNames,
                    serialList: res.data.serialList,
                    searchChartLoading: false,
                    tableLoading: false,
                    alertVisible: false,
                    isSearch: true,
                    eduinspectPointsavg: res.data.eduinspectPointsavg
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

        this.getSchoolLevelByEduId(sessionStorage.getItem("departmentId"), 1)
    

        getDepartmentApi(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                this.setState({
                    countyList: res.data
                });
            }).catch((e) => {
                console.log(e);
            })

    }

    searchSubmit = (e) => {
        var schoolLevel;
        var departmentId;
        e.preventDefault();
        this.props.form.validateFields((err, values) => {

            if (values.deadline == undefined && values.schoolLevel == undefined) {
                message.error('请至少填写一项条件再进行搜索');
            } else {
                if (values.schoolLevel != undefined) {
                    schoolLevel = values.schoolLevel
                }

                if(!isNaN(values.county)){
                    departmentId = values.county
                }else{
                    departmentId = -parseInt(sessionStorage.getItem("departmentId"))
                }
                this.setState({
                    tableLoading: true
                });
                let columnData = [];
                getSchoolInspectCompositeRankApi(departmentId, schoolLevel, this.state.startTime, this.state.endTime)
                    .then((res) => {
                        if (res.data.length == 0) {
                            this.setState({
                                columnData: [],
                                chartSearchData: [],
                                tableLoading: false,
                                isSearch: false
                            });
                        } else {
                            let chartSearchData = {
                                key: [],
                                value: [],
                            };
                            res.data.forEach((item, index) => {
                                columnData.push({
                                    key: index + 1,
                                    schoolname: item.schoolname,
                                    schoolInspectCompositePoints: item.schoolInspectCompositePoints,
                                    departmentName: item.departmentName,
                                    inspectnum: item.inspectnum,
                                    inspectnofinishednum: item.inspectnofinishednum
                                });
                                chartSearchData.key.push(item.schoolname);
                                chartSearchData.value.push(item.schoolInspectCompositePoints);
                            });
                            this.setState({
                                columnData: columnData,
                                searchChartLoading: false,
                                chartSearchData: chartSearchData,
                                tableLoading: false,
                                alertVisible: false,
                                isSearch: true
                            });
                            if(values.average == 1){
                                let columnDataAvg = [];
                                let columnDataTemp = this.state.columnData;
                                let sum = 0;
                                for(let i = 0;i < columnDataTemp.length; i++){
                                    sum += columnDataTemp[i].schoolInspectCompositePoints;
                                }
                                let avg = sum / columnDataTemp.length;
                                let index = 1;
                                for(let i = 0;i < columnDataTemp.length;i ++){
                                    if(columnDataTemp[i].schoolInspectCompositePoints <= avg){
                                        columnDataTemp[i].key = index++;
                                        columnDataAvg.push(columnDataTemp[i]);
                                    }
                                }
                                this.setState({
                                    columnData: columnDataAvg
                                })
                            }
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });


                getSchoolInspectCompositeRank2Api(departmentId, schoolLevel, this.state.startTime, this.state.endTime)
                    .then((res) => {
                        if (res.data.serialList.length == 0) {
                            this.setState({
                                schoolResult: [],
                                schoolName: [],
                                serialList: [],
                                eduinspectPointsavg: "",
                                tableLoading: false,
                                isSearch: false
                            });
                        } else {
                            this.setState({
                                schoolResult: res.data.schoolResults,
                                schoolName: res.data.schoolNames,
                                serialList: res.data.serialList,
                                eduinspectPointsavg: res.data.eduinspectPointsavg,
                                searchChartLoading: false,
                                tableLoading: false,
                                alertVisible: false,
                                isSearch: true
                            });
                            if(values.average == 1){
                                let schoolResultAvg = [];
                                let schoolNameAvg = [];
                                let serialListAvg = [];
                                let t1 = [];
                                let t3 = [];
                                let count = 0;
                                for(let i = 0;i < this.state.schoolResult.length;i++){
                                    for(let j = 0;j < this.state.schoolResult[i].length;j++){
                                        if(parseFloat(this.state.schoolResult[i][j]) <= parseFloat(this.state.eduinspectPointsavg)){
                                            if(count != 0 && count % 5 == 0){
                                                schoolResultAvg.push(t1);
                                                schoolNameAvg.push(t3);
                                                serialListAvg.push(parseInt((count-1) / 5) + 1);
                                                t1 = [];
                                                t3 = [];
                                            }
                                            t1.push(this.state.schoolResult[i][j]);
                                            t3.push(this.state.schoolName[i][j]);
                                            count++;
                                        }
                                    }
                                }
                                if(t1.length != 0){
                                    schoolResultAvg.push(t1);
                                    schoolNameAvg.push(t3);
                                    serialListAvg.push(parseInt((count-1) / 5) + 1);
                                }
                                this.setState({
                                    schoolResult: schoolResultAvg,
                                    schoolName: schoolNameAvg,
                                    serialList: serialListAvg,
                                })
                            }
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });


            }
        });
    }
    clearAll = () => {
        this.setState({
            filteredInfo: null,
            sortedInfo: null,
        });
    }
    handleChange = (pagination, filters, sorter) => {
        this.setState({
            filteredInfo: filters,
            sortedInfo: sorter,
        });
    }
    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
    }
    handleSearchReset = clearFilters => () => {
        clearFilters();
    }
    onRef = (ref) => {
        this.child = ref
    }

    searchReset = () => {
        this.props.form.resetFields();
        // this.setState({
        //     isSearch: false,
        // })
    }

    setFullScreen(opts) {
        this.setState({
            fullScreenVisible: true,
        })
        let fullchart = echarts.init(document.getElementById('fullScreen'))
        fullchart.setOption(opts);
    }

    fullScreenCancel() {
        this.setState({
            fullScreenVisible: false,
        })
    }
    handleSelectTime = (value, dateString) => {
        if (dateString[0] != '' && dateString[1] != '') {
            this.setState({
                startTime: dateString[0],
                endTime: dateString[1],
            })
        }

    }
    handleSelectTime1 = (date, dateString) => {
        console.log(date, dateString)
        const startDate = moment(date).isoWeekday(1).format('YYYY-MM-DD'); //周一日期
        // console.log("周一=====", startDate)
        if (dateString != '') {
            this.setState({
                startTime: startDate,
            })
        }
    }

    handleSelectTime2 = (date, dateString) => {
        console.log(date, dateString)
        const endDate = moment(date).isoWeekday(7).format('YYYY-MM-DD'); //周日日期
        // console.log("周日======", endDate)
        if (dateString != '') {
            this.setState({
                endTime: endDate,
            })
        }
    }

    handleChange2(sorter) {
        console.log("handleChange2()========", sorter)
    }

    getSchoolLevelByEduId(id, allType){
        getSchoolLevelByEduIdApi(id, allType)
            .then((res) => {
                this.setState({
                    branchCampus: res.data,
                });

            })
    }


    render() {
        let branchCampusOptions = [];
        branchCampusOptions.push(<Option value={null} key={-1}>全部</Option>)
        if (this.state.branchCampus.length != 0) {
            branchCampusOptions.push(this.state.branchCampus.map((d, index) =>
                <Option value={d.schoolLevel} key={index}>{d.schoolLevel}</Option>
            ))
        }
        let countyOptions = [];
        let name = sessionStorage.getItem("departmentName")
        let id = parseInt(sessionStorage.getItem("departmentId"))
        countyOptions.push(<Option value={-id} key={-id}>{name.substring(0, name.indexOf("市"))}全市</Option>)
        if(this.state.countyList.length != 0){
            countyOptions.push(this.state.countyList.map((item) =>
                <Option value={item.id} key={item.id}>{item.name}</Option>
            ))
        }
        const { getFieldDecorator, getFieldValue } = this.props.form;
        let { sortedInfo, filteredInfo } = this.state;
        sortedInfo = sortedInfo || {};
        filteredInfo = filteredInfo || {};
        const columnsSearch = [{
            title: "序号",
            dataIndex: "key",
            key: "key"
        }, {
            title: "学校",
            dataIndex: "schoolname",
            key: "schoolname",
            filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                <div className="custom-filter-dropdown">
                    <Input
                        ref={ele => this.searchInput = ele}
                        value={selectedKeys[0]}
                        onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                        onPressEnter={this.handleSearch(selectedKeys, confirm)}
                    />
                    <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                    <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                </div>
            ),
            filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
            onFilter: (value, record) => record.schoolname.toLowerCase().includes(value.toLowerCase()),
            onFilterDropdownVisibleChange: (visible) => {
                if (visible) {
                    setTimeout(() => {
                        this.searchInput.focus();
                    });
                }
            }
        }, 
        sessionStorage.getItem("departmentType") == "教育局" ? 
        {
            title: "区县",
            dataIndex: "departmentName",
            key: "departmentName"
        }:{}, {
            title: "完成巡检次数",
            dataIndex: "inspectnum",
            key: "inspectnum",
        }, {
            title: "未完成巡检次数",
            dataIndex: "inspectnofinishednum",
            key: "inspectnofinishednum",
        }, {
            title: "巡检积分",
            dataIndex: "schoolInspectCompositePoints",
            key: "schoolInspectCompositePoints",
            sorter: (a, b) => a.schoolInspectCompositePoints - b.schoolInspectCompositePoints,
            sortDirections: ['descend', 'ascend'],
        },
        {
            title: '详情',
            dataIndex: 'action',
            key: 'action',
            render: (text, record) => {
                //  console.log("============================", record)
                return (
                    <span>
                        <a
                            onClick={toSchoolUrl.bind(this, record)}
                            // href={this.stahoolUrl}   
                            target="_blank"
                        >
                            查看详情
                        </a>
                        {/* <Button onClick={this.toSchoolUrl.bind(this, record)}> 查看详情</Button> */}
                    </span>
                )
            }
        }]
        let labelCol = {
            sm: { span: 6 },
            xl: { span: 6 },
            xxl: { span: 5 },
        };

        let wrapperCol = {
            sm: { span: 18 },
            xl: { span: 18 },
            xxl: { span: 19 },
        };

        // Excel头部标题
        const header = [
            {
                title: '序号',
                dataIndex: 'key',
                key: 'key',
            }, {
                title: '学校',
                dataIndex: 'schoolname',
                key: 'schoolname',
            }, {
                title: '区县',
                dataIndex: 'departmentName',
                key: 'departmentName',
            }, {
                title: "完成巡检次数",
                dataIndex: "inspectnum",
                key: "inspectnum",
            }, {
                title: "未完成巡检次数",
                dataIndex: "inspectnofinishednum",
                key: "inspectnofinishednum",
            }, {
                title: '巡检积分(分)',
                dataIndex: 'schoolInspectCompositePoints',
                key: 'schoolInspectCompositePoints',
            }
        ]


        return (
            <div style={{ marginBottom: 16 }}>
                <Form style={{
                    padding: '12px',
                    backgroundColor: '#fafafa',
                    borderRadius: 8,
                    marginBottom: 16,
                }}
                    layout="inline"
                    onSubmit={this.searchSubmit}>
                    <Row>
                        <Col span={8}>
                            <FormItem
                                label="截止日期"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("deadline", {
                                    rules: [{
                                        type: 'array',
                                        required: false,
                                    }],
                                    initialValue: [ // 核心代码
                                        moment(this.getBeforeWeekTime(), dateFormat),
                                        moment(this.getBeforeDayTime(), dateFormat),
                                      ],
                                })(
                                    // <RangePicker
                                    //     style={{ width: '100%' }}
                                    //     format="YYYY-MM-DD"
                                    //     onChange={this.handleSelectTime} />
                                    <div>
                                        <WeekPicker picker="week" style={{ width: '48%' }} defaultValue={moment(this.getBeforeWeekTime(), dateFormat)} placeholder="请选择开始日期" onChange={this.handleSelectTime1} />~
                                         <WeekPicker picker="week" style={{ width: '48%' }} defaultValue={moment(this.getBeforeWeekTime(), dateFormat)} placeholder="请选择结束日期" onChange={this.handleSelectTime2} />
                                    </div>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8}>
                            <FormItem
                                label="学校类型"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("schoolLevel", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请选择学校类型">
                                        {branchCampusOptions}
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8}>
                        <FormItem
                                label="数值"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("average", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请选择数值情况">
                                        <Option value={0} key={0}>所有</Option>
                                        <Option value={1} key={1}>低于平均值</Option>
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        {sessionStorage.getItem("departmentType") == "教育局" ? (
                            <Col span={8}>
                            <FormItem
                                label="区县"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("county", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请选择区县"
                                        onSelect = {(e) => {
                                            if(e < 0){
                                                this.getSchoolLevelByEduId(parseInt(sessionStorage.getItem("departmentId")), 1)
                                            }else {
                                                this.getSchoolLevelByEduId(e, 0)
                                            }
                                        }}>
                                        {countyOptions}
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        )
                        :null
                        }
                        <Col>
                            <FormItem
                                style={{ float: 'right' }}>
                                <Button type="primary" htmlType="submit">搜索</Button>
                                <Button style={{ marginLeft: 8 }} onClick={this.searchReset}>清空</Button>
                                <Button type="primary" style={{ marginLeft: 8 }} onClick={() =>  {
                                    exportExcel(header, this.state.columnData, "学校巡检积分排名.xlsx")
                                    }}>导出Excel
                                </Button> 
                            </FormItem>
                        </Col>
                    </Row>
                </Form>
                <div>
                    {
                        this.state.isSearch ?
                            (
                                <div style={{
                                    marginBottom: 16,
                                    padding: 16,
                                    width: '100%',
                                    height: 350,
                                    border: '1px solid',
                                    borderColor: '#f5f5f5'
                                }}>
                                    <Skeleton loading={this.state.searchChartLoading} active>
                                      
                                        <ChartSearchEduInspectCompositeRank
                                            that={this}
                                            schoolName={this.state.schoolName}
                                            schoolResult={this.state.schoolResult}
                                            serialList={this.state.serialList}
                                            eduinspectPointsavg={this.state.eduinspectPointsavg}
                                            divId={'chartSearchEduInspectCompositeRank'}
                                        />
                                    </Skeleton>
                                </div>
                            ) : null
                    }
                    {
                        this.state.isSearch ? 
                        (
                            <Alert
                            message="学校巡检积分说明"
                            description={"学校巡检积分=在统计范围内，该学校实际完成巡检项目次数-未完成巡检项目次数*0.5"}
                            type="info"
                            showIcon/>
                        ) : null
                    }
                    
                    <Table
                        dataSource={this.state.columnData}
                        columns={columnsSearch}
                        loading={this.state.tableLoading}
                        locale={{ emptyText: '暂无数据' }}
                        onChange={this.handleChange2}
                        rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                        pagination={{  //分页
                            total: this.state.searchData.length, //数据总数量
                            defaultPageSize: 10, //默认显示几条一页
                            //pageSize: 10,
                            showTotal: function (total) {  //设置显示一共几条数据
                                return '共 ' + total + ' 条数据';
                            },
                            showSizeChanger: true,
                            showQuickJumper: true,
                            pageSizeOptions: [5, 10, 20, 30]
                        }} />
                </div>
            </div>
        );
    }
}

const EduInspectCompositeRank = Form.create()(eduInspectComposite);


class ChartSearch extends Component {
    constructor(props) {
        super(props);
        this.state = {
            schoolResult: props.schoolResult || [],
            schoolResult2: props.schoolResult2 || [],
            //schoolResult: [[1281.0, 600.0, 72.0, 87, 94], [63.0, 0.0, -1.5, 98, 391]],
            schoolName: props.schoolName || [],
            //schoolName: [[" 丰惠镇中心幼儿园", "第二实验幼儿园盛丰园区", "第一实验幼儿园和润花园区", "第一实验幼儿园新上海园区", "梯度中学"], ["第一实验幼儿园新上海园区", "梯度中学", "上浦镇中心幼儿园", "第一实验幼儿园新上海园区", "梯度中学"]],
            serialList: props.serialList || [],
            eduinspectnumavg: props.eduinspectnumavg || [],
            eduinspectnumsum: props.eduinspectnumsum || 0,
            //serialList: ["1", "2"],
            that: props.that,
            currentIndex: 0,
            divId: props.divId,
            data1: 0,
            schoolNamePart: []
        };

        // console.log("props===========", props)
    }

    componentWillReceiveProps(props) {
        console.log("componentWillReceiveProps===============")
        if (JSON.stringify(props.schoolName) != JSON.stringify(this.state.schoolName) && props.serialList.length > 0) {
            // console.log("componentWillReceiveProps===============")
            this.setState({
                that: props.that,
                schoolResult: props.schoolResult,
                schoolResult2: props.schoolResult2,
                schoolName: props.schoolName,
                serialList: props.serialList,
                eduinspectnumavg: props.eduinspectnumavg,
                eduinspectnumsum: props.eduinspectnumsum,
            }, () => {
                this.drawChart()
            })
        }
    }

    componentDidMount() {
        let optionData = [];
        if (this.state.schoolName.length != 0) {
            this.drawChart();
        }
    }




    drawChart() {


      var chart = echarts.init(document.getElementById('chartSearch'));

      let option = {

            baseOption: {
                timeline: {
                    axisType: 'category',
                    currentIndex: 0,
                    triggerEvent: true,
                    playInterval: 1000,
                    data: this.state.serialList
                   // data:  ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14"]
                },
                  title: {
                    text: '学校巡检次数排名',
                    left: 'center',
                    top: '10px',
                    subtext:'完成总次数: ' + this.state.eduinspectnumsum + '次',
                    subtextStyle: {
                        fontSize: 16
                    }
                },
                legend: [
                    {
                        // x: '100px',
                        left:'5%',
                        padding: 5,
                        data: [{name: '巡检计划次数'}, {name:'巡检完成次数'}]
                    }
                 
                ],
                color: ['#3398DB'],
                //color: ['#00FF004'],
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                        type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                    }
                },
                toolbox: {
                    show: true,
                    feature: {
                        dataZoom: {
                            yAxisIndex: 'none'
                        },
                        dataView: { readOnly: false },
                        magicType: { type: ['line', 'bar'] },
                        restore: {},
                        saveAsImage: {}
                    }
                },
                grid: {
                    left: '5%',
                    right: '5%',
                    bottom: '50px',
                    top: '90px',
                    containLabel: true
                },
                xAxis: [
                    {
                        type: 'category',
                        data: [],
                        axisTick: {
                            alignWithLabel: true
                        },
                        axisLabel: {
                            textStyle: {
                                fontSize: 16
                            }
                        }
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        axisLabel: {
                            formatter: '{value}次',
                            textStyle: {
                                fontSize: 16
                            }
                        }
                    }
                ],

                series: [
                    { name: '巡检计划次数',  type: 'bar'},
                    { name: '巡检完成次数',  type: 'bar'}
                ],

            },
           
            options: []        
        };
        for (var i = 0; i < this.state.schoolResult2.length; i++) {
            let schoolNameList = [];
            for(var j = 0;j < this.state.schoolName[i].length; j++){
                let arr = this.state.schoolName[i][j].split("\n");
                schoolNameList.push(arr[0]);
            }
            
            option.options.push({
                xAxis: {
                    data: sessionStorage.getItem("departmentType") == "教育局" ? this.state.schoolName[i]
                    : schoolNameList
                },
                series: [
                    {
                        name: '巡检计划次数',
                        type: 'bar',
                        data: this.state.schoolResult2[i],
                        barGap: '100%',
                        barMaxWidth: 25,
                        animation: false,
                        itemStyle:
                        {
                            color: 'rgb(255, 70, 131)',
                            normal: {
                                label: {
                                    show: true, //开启显示
                                    position: 'top', //在上方显示
                                    textStyle: { //数值样式
                                        color: 'black',
                                        fontSize: 14
                                    }
                                }
                            }
                        },
                        showBackground: true,
                        backgroundStyle: {
                            color: 'rgba(180, 180, 180, 0.2)'
                        },
                    },
                    {
                        name: '巡检完成次数',
                        type: 'bar',
                        data: this.state.schoolResult[i],
                        barGap: '100%',
                        barMaxWidth: 25,
                        animation: false,
                        itemStyle:
                            {
                                //color: 'rgb(255, 70, 131)',
                                //color: '#FFD700',
                                normal: {
                                    color: '#FFD700',
                                    label: {
                                        show: true, //开启显示
                                        position: 'top', //在上方显示
                                        textStyle: { //数值样式
                                            color: 'black',
                                            fontSize: 14
                                        }
                                    }
                                }
                            },
                        showBackground: true,
                        backgroundStyle: {
                            color: 'rgba(180, 180, 180, 0.2)'
                        },
                        // markLine: {
                        //     label: { formatter: '平均值: ' + this.state.eduinspectnumavg },
                        //     symbol: 'none',
                        //     data: [{
                        //         type: 'average',
                        //         name: '平均值',
                        //     }]
                        // },
            
                        markPoint: {
                            data: [
                                {
                                    type: 'max', name: '最大值'
                                }, {
                                    type: 'min', name: '最小值'
                                }
                            ]
                        }
                    }
                ]
            })
        }
        
        
        chart.setOption(option);
       
        
    }


    render() {
        let chartStyle = {
            height: '100%',
            width: '100%',
        };
        return (<div id={this.state.divId} style={chartStyle} />)
    }
}

class ChartSearchEduInspectFinishedRate extends Component {

    constructor(props) {
        super(props);
        this.state = {
            schoolResult: props.schoolResult || [],
            //schoolResult: [[1281.0, 600.0, 72.0, 87, 94], [63.0, 0.0, -1.5, 98, 391]],
            schoolName: props.schoolName || [],
            //schoolName: [[" 丰惠镇中心幼儿园", "第二实验幼儿园盛丰园区", "第一实验幼儿园和润花园区", "第一实验幼儿园新上海园区", "梯度中学"], ["第一实验幼儿园新上海园区", "梯度中学", "上浦镇中心幼儿园", "第一实验幼儿园新上海园区", "梯度中学"]],
            serialList: props.serialList || [],
            eduinspectRatesavg: props.eduinspectRatesavg || [],
            //serialList: ["1", "2"],
            that: props.that,
            currentIndex: 0,
            divId: props.divId,
            data1: 0,
            schoolNamePart: []
        };


    }

    componentWillReceiveProps(props) {

        if (JSON.stringify(props.schoolName) != JSON.stringify(this.state.schoolName) && props.serialList.length > 0) {
            this.setState({
                that: props.that,
                schoolResult: props.schoolResult,
                schoolName: props.schoolName,
                serialList: props.serialList,
                eduinspectRatesavg: props.eduinspectRatesavg
            }, () => {
                this.drawChart()
            })
        }
    }

    componentDidMount() {
        let optionData = [];
        if (this.state.schoolName.length != 0) {
            this.drawChart();
        }
    }




    drawChart() {

        let optionData = [];

        let chart = echarts.init(document.getElementById('chartSearchEduInspectFinishedRate'));
        let option = {

            baseOption: {
                timeline: {
                    axisType: 'category',
                    triggerEvent: true,
                    playInterval: 1000,
                    data: this.state.serialList
                },
                title: {
                    text: '学校巡检完成率排名',
                    left: 'center',
                    top: '10px',
                    subtext:'平均值: ' + this.state.eduinspectRatesavg +'%',
                    subtextStyle: {
                        fontSize: 16
                    }
                },
                color: ['#3398DB'],
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                        type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                    }
                },
                toolbox: {
                    show: true,
                    feature: {
                        dataZoom: {
                            yAxisIndex: 'none'
                        },
                        dataView: { readOnly: false },
                        magicType: { type: ['line', 'bar'] },
                        restore: {},
                        saveAsImage: {}
                    }
                },
                grid: {
                    left: '5%',
                    right: '5%',
                    bottom: '50px',
                    top: '90px',
                    containLabel: true
                },
                xAxis: [
                    {
                        type: 'category',
                        data: this.state.schoolNamePart,
                        axisTick: {
                            alignWithLabel: true
                        },
                        axisLabel: {
                            textStyle: {
                                fontSize: 16
                            }
                        }
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        axisLabel: {
                            formatter: '{value}%',
                            textStyle: {
                                fontSize: 16
                            }
                        }
                    }
                ],

                series: [
                    { name: '巡检完成率', type: 'bar' },
                ],

            },
            options: []
        };


        for (var i = 0; i < this.state.schoolResult.length; i++) {
            let schoolNameList = [];
            for(var j = 0;j < this.state.schoolName[i].length; j++){
                let arr = this.state.schoolName[i][j].split("\n");
                schoolNameList.push(arr[0]);
            }
            
            option.options.push({
                xAxis: {
                    data: sessionStorage.getItem("departmentType") == "教育局" ? this.state.schoolName[i]
                    : schoolNameList
                },
                series: [                
                    {
                        name: '巡检完成率',
                        type: 'bar',
                        data: this.state.schoolResult[i],
                        barGap: '100%',
                        barMaxWidth: 25,
                        animation: false,
                        itemStyle:
                            {
                                color: 'rgb(255, 70, 131)',
                                //color: '#FFD700',
                                normal: {
                                   // color: '#FFD700',
                                    label: {
                                        show: true, //开启显示
                                        position: 'top', //在上方显示
                                        textStyle: { //数值样式
                                            color: 'black',
                                            fontSize: 14
                                        }
                                    }
                                }
                            },
                        showBackground: true,
                        backgroundStyle: {
                            color: 'rgba(180, 180, 180, 0.2)'
                        },
                        // markLine: {
                        //     label: { formatter: '平均值: ' + this.state.eduinspectRatesavg },
                        //     symbol: 'none',
                        //     data: [{
                        //         type: 'average',
                        //         name: '平均值',
                        //     }]
                        // },
            
                        markPoint: {
                            data: [
                                {
                                    type: 'max', name: '最大值'
                                }, {
                                    type: 'min', name: '最小值'
                                }
                            ]
                        }
                    }
                ]
            })
        }
        chart.setOption(option);
    
    }


    render() {
        let chartStyle = {
            height: '100%',
            width: '100%',
        };
        return (<div id={this.state.divId} style={chartStyle} />)
    }

}

class ChartSearchEduInspectCompositeRank extends Component {
    constructor(props) {
        super(props);
        this.state = {
            schoolResult: props.schoolResult || [],
            //schoolResult2: props.schoolResult2 || [],
            //schoolResult: [[1281.0, 600.0, 72.0, 87, 94], [63.0, 0.0, -1.5, 98, 391]],
            schoolName: props.schoolName || [],
            //schoolName: [[" 丰惠镇中心幼儿园", "第二实验幼儿园盛丰园区", "第一实验幼儿园和润花园区", "第一实验幼儿园新上海园区", "梯度中学"], ["第一实验幼儿园新上海园区", "梯度中学", "上浦镇中心幼儿园", "第一实验幼儿园新上海园区", "梯度中学"]],
            serialList: props.serialList || [],
            eduinspectPointsavg: props.eduinspectPointsavg,
            //serialList: ["1", "2"],
            that: props.that,
            currentIndex: 0,
            divId: props.divId,
            data1: 0,
            schoolNamePart: []
        };
    }

    componentWillReceiveProps(props) {
        if (JSON.stringify(props.schoolName) != JSON.stringify(this.state.schoolName) && props.serialList.length > 0) {
            this.setState({
                that: props.that,
                schoolResult: props.schoolResult,
                schoolName: props.schoolName,
                serialList: props.serialList,
                eduinspectPointsavg: props.eduinspectPointsavg,
            }, () => {
                this.drawChart()
            })
        }
    }

    componentDidMount() {
        let optionData = [];
        if (this.state.schoolName.length != 0) {
            this.drawChart();
        }
    }




    drawChart() {

        let optionData = [];

        let chart = echarts.init(document.getElementById('chartSearchEduInspectCompositeRank'));
        let option = {

            baseOption: {
                timeline: {
                    axisType: 'category',
                    triggerEvent: true,
                    playInterval: 1000,
                    data: this.state.serialList
                },
                title: {
                    text: '学校巡检积分排名',
                    left: 'center',
                    top: '10px',
                    subtext:'平均值: ' + this.state.eduinspectPointsavg +'分',
                    subtextStyle: {
                        fontSize: 16
                    }
                },
                color: ['#3398DB'],
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                        type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                    }
                },
                toolbox: {
                    show: true,
                    feature: {
                        dataZoom: {
                            yAxisIndex: 'none'
                        },
                        dataView: { readOnly: false },
                        magicType: { type: ['line', 'bar'] },
                        restore: {},
                        saveAsImage: {}
                    }
                },
                grid: {
                    left: '5%',
                    right: '5%',
                    bottom: '50px',
                    top: '90px',
                    containLabel: true
                },
                xAxis: [
                    {
                        type: 'category',
                        data: this.state.schoolNamePart,
                        axisTick: {
                            alignWithLabel: true
                        },
                        axisLabel: {
                            textStyle: {
                                fontSize: 16
                            }
                        }
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        axisLabel: {
                            formatter: '{value}分',
                            textStyle: {
                                fontSize: 16
                            }
                        }
                    }
                ],

                series: [
                    { name: '巡检积分', type: 'bar' },
                ],

            },
            options: []
        };

        
        for (var i = 0; i < this.state.schoolResult.length; i++) {
            let schoolNameList = [];
            for(var j = 0;j < this.state.schoolName[i].length; j++){
                let arr = this.state.schoolName[i][j].split("\n");
                schoolNameList.push(arr[0]);
            }
            
            option.options.push({
                xAxis: {
                    data: sessionStorage.getItem("departmentType") == "教育局" ? this.state.schoolName[i]
                    : schoolNameList
                },
                series: [                
                    {
                        name: '巡检积分',
                        type: 'bar',
                        data: this.state.schoolResult[i],
                        barGap: '100%',
                        barMaxWidth: 25,
                        animation: false,
                        itemStyle:
                            {
                                color: 'rgb(255, 70, 131)',
                                //color: '#FFD700',
                                normal: {
                                   // color: '#FFD700',
                                    label: {
                                        show: true, //开启显示
                                        position: 'top', //在上方显示
                                        textStyle: { //数值样式
                                            color: 'black',
                                            fontSize: 14
                                        }
                                    }
                                }
                            },
                        showBackground: true,
                        backgroundStyle: {
                            color: 'rgba(180, 180, 180, 0.2)'
                        },
                        // markLine: {
                        //     label: { formatter: '平均值: ' + this.state.eduinspectPointsavg },
                        //     symbol: 'none',
                        //     data: [{
                        //         type: 'average',
                        //         name: '平均值',
                        //     }]
                        // },
            
                        markPoint: {
                            data: [
                                {
                                    type: 'max', name: '最大值'
                                }, {
                                    type: 'min', name: '最小值'
                                }
                            ]
                        }
                    }
                ]
            })
        }

        
        chart.setOption(option);
     

    }



    render() {
        let chartStyle = {
            height: '100%',
            width: '100%',
        };
        return (<div id={this.state.divId} style={chartStyle} />)
    }
}

//校巡更次数排名
class eduPatrolNumRank extends Component {
    constructor(props) {
        super(props);
        this.state = {
            alertVisible: false, //提示
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            tableLoading: true,
            filteredInfo: null,
            sortedInfo: null,
            searchData: [],
            schoolLevel: [],
            countyList: [],
            searchChartLoading: true,
            chartSearchData: {},
            chartSearchAvg: "",
            startTime: "",
            endTime: "",
            isSearch: false,
            departmentId: sessionStorage.getItem("departmentId")
        };
    }
    componentWillMount() {
    }
    componentDidMount() {
        this.refreshData();
    }
    getBeforeDayTime() {
        var time = (new Date()).getTime() - 24 * 60 * 60 * 1000;
        var beforeday = new Date(time); // 获取的是前一天日期

        beforeday = beforeday.getFullYear() + "-" + (beforeday.getMonth() + 1 > 9
            ? (beforeday.getMonth() + 1) : "0" + (beforeday.getMonth()+1)) + "-" + (beforeday.getDate() > 9
                ? (beforeday.getDate()) : "0" + (beforeday.getDate())); //字符串拼接转格式：例如2018-08-19
        
        return beforeday
    }
    getBeforeWeekTime() {
        var time = (new Date()).getTime() - 24 * 60 * 60 * 1000 * 7;
        var beforeweek = new Date(time); // 获取的是前一周日期

        beforeweek = beforeweek.getFullYear() + "-" + (beforeweek.getMonth() + 1 > 9
            ? (beforeweek.getMonth() + 1) : "0" + (beforeweek.getMonth() + 1)) + "-" + (beforeweek.getDate() > 9
                ? (beforeweek.getDate()) : "0" + (beforeweek.getDate())); //字符串拼接转格式：例如2018-08-19
        return beforeweek
    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        let columnData = [];
        let schoolLevel;
        var startTime = this.getBeforeWeekTime()
        var endTime = this.getBeforeDayTime()

        let departmentId = -sessionStorage.getItem("departmentId")

        getEduPatrolNumRankApi(departmentId, schoolLevel, startTime, endTime)
            .then((res) => {
                res.data.edupatrolnumrankList.forEach((item, index) => {
                    columnData.push({
                        key: index + 1,
                        schoolname: item.schoolname,
                        patrolnum: item.patrolnum,
                        patrolplanum: item.patrolplanum,
                        departmentName: item.departmentName
                    });
                });
                this.setState({
                    columnData: columnData,
                    startTime: startTime,
                    endTime: endTime,
                    tableLoading: false,
                    alertVisible: false,
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });


            getEduPatrolNumRankApi2(departmentId, schoolLevel, startTime, endTime)
            .then((res) => {
                if (res.data.serialList.length == 0) {
                    this.setState({
                        schoolResult: [],
                        schoolResult2: [],
                        schoolName: [],
                        serialList: [],
                        chartAvg: "",
                        edupatrolnumsum:  "",
                        tableLoading: false,
                        isSearch: false
                    });
                } else {
                    this.setState({
                        schoolResult: res.data.schoolResults,
                        schoolResult2: res.data.schoolResults2,
                        schoolName: res.data.schoolNames,
                        serialList: res.data.serialList,
                        chartAvg: res.data.edupatrolnumavg,
                        edupatrolnumsum: res.data.edupatrolnumsum,
                        searchChartLoading: false,
                        tableLoading: false,
                        alertVisible: false,
                        isSearch: true
                    });
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });


        this.getSchoolLevelByEduId(sessionStorage.getItem("departmentId"), 1)
    

        getDepartmentApi(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                this.setState({
                    countyList: res.data
                });
            }).catch((e) => {
                console.log(e);
            })
    }

    searchSubmit = (e) => {
        var schoolLevel;
        var departmentId;
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            console.log("values==============", values);

            if (values.deadline == undefined && values.schoolLevel == undefined) {
                message.error('请至少填写一项条件再进行搜索');
            } else {
                if (values.schoolLevel != undefined) {
                    schoolLevel = values.schoolLevel
                }
                if(!isNaN(values.county)){
                    departmentId = values.county
                }else{
                    departmentId = -parseInt(sessionStorage.getItem("departmentId"))
                }
                this.setState({
                    tableLoading: true
                });
                let columnData = [];
                getEduPatrolNumRankApi(departmentId, schoolLevel, this.state.startTime, this.state.endTime)
                    .then((res) => {
                        res.data.edupatrolnumrankList.forEach((item, index) => {
                            columnData.push({
                                key: index + 1,
                                schoolname: item.schoolname,
                                patrolnum: item.patrolnum,
                                patrolplanum: item.patrolplanum,
                                departmentName: item.departmentName
                            });
                        });
                        this.setState({
                            columnData: columnData,
                            tableLoading: false,
                            alertVisible: false,
                        });
                        // 获取低于平均值的学校
                        if(values.average == 1){
                            let columnDataAvg = [];
                            let columnDataTemp = this.state.columnData;
                            let sum = 0;
                            for(let i = 0;i < columnDataTemp.length; i++){
                                sum += columnDataTemp[i].patrolnum;
                            }
                            let avg = sum / columnDataTemp.length;
                            let index = 1;
                            for(let i = 0;i < columnDataTemp.length;i ++){
                                if(columnDataTemp[i].patrolnum <= avg){
                                    columnDataTemp[i].key = index++;
                                    columnDataAvg.push(columnDataTemp[i]);
                                }
                            }
                            this.setState({
                                columnData: columnDataAvg
                            })
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });
                getEduPatrolNumRankApi2(departmentId, schoolLevel, this.state.startTime, this.state.endTime)
                    .then((res) => {
                        if (res.data.serialList.length == 0) {
                            this.setState({
                                schoolResult: [],
                                schoolResult2: [],
                                schoolName: [],
                                serialList: [],
                                chartAvg: "",
                                edupatrolnumsum: "",
                                tableLoading: false,
                                isSearch: false
                            });
                        } else {
                            this.setState({
                                schoolResult: res.data.schoolResults,
                                schoolResult2: res.data.schoolResults2,
                                schoolName: res.data.schoolNames,
                                serialList: res.data.serialList,
                                chartAvg: res.data.edupatrolnumavg,
                                edupatrolnumsum: res.data.edupatrolnumsum,
                                searchChartLoading: false,
                                tableLoading: false,
                                alertVisible: false,
                                isSearch: true
                            });
                            if(values.average == 1){
                                let schoolResultAvg = [];
                                let schoolResult2Avg = [];
                                let schoolNameAvg = [];
                                let serialListAvg = [];
                                let t1 = [];
                                let t2 = [];
                                let t3 = [];
                                let count = 0;
                                for(let i = 0;i < this.state.schoolResult.length;i++){
                                    for(let j = 0;j < this.state.schoolResult[i].length;j++){
                                        if(this.state.schoolResult[i][j] <= parseInt(this.state.chartAvg)){
                                            if(count != 0 && count % 5 == 0){
                                                schoolResultAvg.push(t1);
                                                schoolResult2Avg.push(t2);
                                                schoolNameAvg.push(t3);
                                                serialListAvg.push(parseInt((count-1) / 5) + 1);
                                                t1 = [];
                                                t2 = [];
                                                t3 = [];
                                            }
                                            t1.push(this.state.schoolResult[i][j]);
                                            t2.push(this.state.schoolResult2[i][j]);
                                            t3.push(this.state.schoolName[i][j]);
                                            count++;
                                        }
                                    }
                                }
                                if(t1.length != 0){
                                    schoolResultAvg.push(t1);
                                    schoolResult2Avg.push(t2);
                                    schoolNameAvg.push(t3);
                                    serialListAvg.push(parseInt((count-1) / 5) + 1);
                                }
                                this.setState({
                                    schoolResult: schoolResultAvg,
                                    schoolResult2: schoolResult2Avg,
                                    schoolName: schoolNameAvg,
                                    serialList: serialListAvg,
                                })
                            }
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });

                    

            }
        });
    }
    clearAll = () => {
        this.setState({
            filteredInfo: null,
            sortedInfo: null,
        });
    }
    handleChange = (pagination, filters, sorter) => {
        this.setState({
            filteredInfo: filters,
            sortedInfo: sorter,
        });
    }
    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
    }
    handleSearchReset = clearFilters => () => {
        clearFilters();
    }
    onRef = (ref) => {
        this.child = ref
    }

    searchReset = () => {
        this.props.form.resetFields();
    }

    setFullScreen(opts) {
        this.setState({
            fullScreenVisible: true,
        })
        let fullchart = echarts.init(document.getElementById('fullScreen'))
        fullchart.setOption(opts);
    }

    fullScreenCancel() {
        this.setState({
            fullScreenVisible: false,
        })
    }
    handleSelectTime = (value, dateString) => {
        if (dateString[0] != '' && dateString[1] != '') {
            this.setState({
                startTime: dateString[0],
                endTime: dateString[1],
            })
        }

    }

    handleChange2() {
        console.log("handleChange2()=========================")
    }

    getSchoolLevelByEduId(id, allType){
        getSchoolLevelByEduIdApi(id, allType)
            .then((res) => {
                this.setState({
                    schoolLevel: res.data,
                });

            })
    }


    render() {
        let schoolLevelOptions = [];
        schoolLevelOptions.push(<Option value={null} key={-1}>全部</Option>)
        if (this.state.schoolLevel.length != 0) {
            schoolLevelOptions.push(this.state.schoolLevel.map((d, index) =>
                <Option value={d.schoolLevel} key={index}>{d.schoolLevel}</Option>
            ))
        }
        let countyOptions = [];
        let name = sessionStorage.getItem("departmentName")
        let id = parseInt(sessionStorage.getItem("departmentId"))
        countyOptions.push(<Option value={-id} key={-id}>{name.substring(0, name.indexOf("市"))}全市</Option>)
        if(this.state.countyList.length != 0){
            countyOptions.push(this.state.countyList.map((item) =>
                <Option value={item.id} key={item.id}>{item.name}</Option>
            ))
        }
        const { getFieldDecorator, getFieldValue } = this.props.form;
        let { sortedInfo, filteredInfo } = this.state;
        sortedInfo = sortedInfo || {};
        filteredInfo = filteredInfo || {};
        const columnsSearch = [{
            title: "序号",
            dataIndex: "key",
            key: "key"
        }, {
            title: "学校",
            dataIndex: "schoolname",
            key: "schoolname",
            filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                <div className="custom-filter-dropdown">
                    <Input
                        ref={ele => this.searchInput = ele}
                        value={selectedKeys[0]}
                        onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                        onPressEnter={this.handleSearch(selectedKeys, confirm)}
                    />
                    <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                    <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                </div>
            ),
            filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
            onFilter: (value, record) => record.schoolname.toLowerCase().includes(value.toLowerCase()),
            onFilterDropdownVisibleChange: (visible) => {
                if (visible) {
                    setTimeout(() => {
                        this.searchInput.focus();
                    });
                }
            }
        }, 
        sessionStorage.getItem("departmentType") == "教育局" ? 
        {
            title: "区县",
            dataIndex: "departmentName",
            key: "departmentName"
        }:{}, {
            title: "巡更计划次数",
            dataIndex: "patrolplanum",
            key: "patrolplanum",
            sorter: (a, b) => a.patrolplanum - b.patrolplanum,
            sortDirections: ['descend', 'ascend'],

        }, {
            title: "巡更实际次数",
            dataIndex: "patrolnum",
            key: "patrolnum",
            sorter: (a, b) => a.patrolnum - b.patrolnum,
            sortDirections: ['descend', 'ascend'],

        },
        {
            title: '详情',
            dataIndex: 'action',
            key: 'action',
            render: (text, record) => {
                //  console.log("============================", record)
                return (
                    <span>
                        <a
                            onClick={toSchoolUrl.bind(this, record)}
                            // href={this.stahoolUrl}   
                            target="_blank"
                        >
                            查看详情
                        </a>
                        {/* <Button onClick={this.toSchoolUrl.bind(this, record)}> 查看详情</Button> */}
                    </span>
                )
            }
        }]
        let labelCol = {
            sm: { span: 6 },
            xl: { span: 6 },
            xxl: { span: 5 },
        };

        let wrapperCol = {
            sm: { span: 18 },
            xl: { span: 18 },
            xxl: { span: 19 },
        };

        // Excel头部标题
        const header = [
            {
                title: '序号',
                dataIndex: 'key',
                key: 'key',
            }, {
                title: '学校',
                dataIndex: 'schoolname',
                key: 'schoolname',
            }, {
                title: '区县',
                dataIndex: 'departmentName',
                key: 'departmentName',
            }, {
                title: '巡更计划次数(次)',
                dataIndex: 'patrolplanum',
                key: 'patrolplanum',
            }, {
                title: '巡更实际次数(次)',
                dataIndex: 'patrolnum',
                key: 'patrolnum',
            }
        ]


        return (
            <div style={{ marginBottom: 16 }}>
                <Form style={{
                    padding: '12px',
                    backgroundColor: '#fafafa',
                    borderRadius: 8,
                    marginBottom: 16,
                }}
                    layout="inline"
                    onSubmit={this.searchSubmit}>
                    <Row>
                        <Col span={8}>
                            <FormItem
                                label="截止日期"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("deadline", {
                                    rules: [{
                                        type: 'array',
                                        required: false,
                                    }],
                                    initialValue: [ // 核心代码
                                        moment(this.getBeforeWeekTime(), dateFormat),
                                        moment(this.getBeforeDayTime(), dateFormat),
                                      ],
                                })(
                                    <RangePicker
                                        style={{ width: '100%' }}
                                        format="YYYY-MM-DD"
                                        onChange={this.handleSelectTime} />
                                )}
                            </FormItem>
                        </Col>
                        {sessionStorage.getItem("departmentType") == "教育局" ? (
                            <Col span={5}>
                            <FormItem
                                label="区县"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("county", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请选择区县"
                                        onSelect = {(e) => {
                                            if(e < 0){
                                                this.getSchoolLevelByEduId(parseInt(sessionStorage.getItem("departmentId")), 1)
                                            }else {
                                                this.getSchoolLevelByEduId(e, 0)
                                            }
                                        }}>
                                        {countyOptions}
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        )
                        :null
                        }
                        <Col span={8}>
                            <FormItem
                                label="学校类型"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("schoolLevel", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请选择学校类型">
                                        {schoolLevelOptions}
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8}>
                        <FormItem
                                label="数值"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("average", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请选择数值情况">
                                        <Option value={0} key={0}>所有</Option>
                                        <Option value={1} key={1}>低于平均值</Option>
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        <Col>
                            <FormItem
                                style={{ float: 'right' }}>
                                <Button type="primary" htmlType="submit">搜索</Button>
                                <Button style={{ marginLeft: 8 }} onClick={this.searchReset}>清空</Button>
                                <Button type="primary" style={{ marginLeft: 8 }} onClick={() =>  {
                                    exportExcel(header, this.state.columnData, "学校巡更次数排名.xlsx")
                                    }}>导出Excel
                                </Button>
                            </FormItem>
                        </Col>
                    </Row>
                </Form>
                <div>
                    {
                        this.state.isSearch ?
                            (
                                <div style={{
                                    marginBottom: 16,
                                    padding: 16,
                                    width: '100%',
                                    height: 350,
                                    border: '1px solid',
                                    borderColor: '#f5f5f5'
                                }}>
                                    <Skeleton loading={this.state.searchChartLoading} active>
                                        <ChartSearchPatrolNum
                                            that={this}
                                            schoolName={this.state.schoolName}
                                            schoolResult={this.state.schoolResult}
                                            schoolResult2={this.state.schoolResult2}
                                            serialList={this.state.serialList}
                                            chartAvg={this.state.chartAvg}
                                            edupatrolnumsum={this.state.edupatrolnumsum}
                                            divId={'chartSearch'} />
                                    </Skeleton>
                                </div>
                            ) : null
                    }
                    <Table
                        dataSource={this.state.columnData}
                        columns={columnsSearch}
                        loading={this.state.tableLoading}
                        locale={{ emptyText: '暂无数据' }}
                        onChange={this.handleChange2}
                        rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                        pagination={{  //分页
                            total: this.state.searchData.length, //数据总数量
                            defaultPageSize: 10, //默认显示几条一页
                            //pageSize: 10,
                            showTotal: function (total) {  //设置显示一共几条数据
                                return '共 ' + total + ' 条数据';
                            },
                            showSizeChanger: true,
                            showQuickJumper: true,
                            pageSizeOptions: [5, 10, 20, 30]
                        }} />
                </div>
            </div>
        );
    }
}
const EduPatrolNumRank = Form.create()(eduPatrolNumRank);

//校巡更次数排名柱状图
class ChartSearchPatrolNum extends Component {
    constructor(props) {
        super(props);
        this.state = {
            schoolResult: props.schoolResult || [],
            schoolResult2: props.schoolResult2 || [],
            //schoolResult: [[1281.0, 600.0, 72.0, 87, 94], [63.0, 0.0, -1.5, 98, 391]],
            schoolName: props.schoolName || [],
            //schoolName: [[" 丰惠镇中心幼儿园", "第二实验幼儿园盛丰园区", "第一实验幼儿园和润花园区", "第一实验幼儿园新上海园区", "梯度中学"], ["第一实验幼儿园新上海园区", "梯度中学", "上浦镇中心幼儿园", "第一实验幼儿园新上海园区", "梯度中学"]],
            serialList: props.serialList || [],
            //serialList: ["1", "2"],
            that: props.that,
            currentIndex: 0,
            divId: props.divId,
            data1: 0,
            schoolNamePart: [],
            chartAvg: props.chartAvg,
            edupatrolnumsum: props.edupatrolnumsum || 0,
        };


    }

    componentWillReceiveProps(props) {

        if (JSON.stringify(props.schoolName) != JSON.stringify(this.state.schoolName) && props.serialList.length > 0) {
            this.setState({
                that: props.that,
                schoolResult: props.schoolResult,
                schoolResult2:props.schoolResult2,
                schoolName: props.schoolName,
                serialList: props.serialList,
                chartAvg: props.chartAvg,
                edupatrolnumsum: props.edupatrolnumsum,
            }, () => {
                this.drawChart()
            })
        }
    }

    componentDidMount() {
        let optionData = [];
        if (this.state.schoolName.length != 0) {
            this.drawChart();
        }
    }




    drawChart() {

        let optionData = [];

        let chart = echarts.init(document.getElementById('chartSearch'));
        let option = {

            baseOption: {
                timeline: {
                    axisType: 'category',
                    triggerEvent: true,
                    playInterval: 1000,
                    data: this.state.serialList
                },
                title: {
                    text: '学校巡更次数排名',
                    left: 'center',
                    top: '10px',
                    subtext:'完成总次数: ' + this.state.edupatrolnumsum +'次',
                    subtextStyle: {
                        fontSize: 16
                    }
                },
                
                legend: {
                    // x: '100px',
                    left:'5%',
                    // y: '2px',
                    // bottom: 'bottom',
                    data: ['巡更计划次数', '巡更实际次数']
                },
                color: ['#3398DB'],
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                        type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                    }
                },
                toolbox: {
                    show: true,
                    feature: {
                        dataZoom: {
                            yAxisIndex: 'none'
                        },
                        dataView: { readOnly: false },
                        magicType: { type: ['line', 'bar'] },
                        restore: {},
                        saveAsImage: {}
                    }
                },
                grid: {
                    left: '5%',
                    right: '5%',
                    bottom: '50px',
                    top: '90px',
                    containLabel: true
                },
                xAxis: [
                    {
                        type: 'category',
                        data: this.state.schoolNamePart,
                        axisTick: {
                            alignWithLabel: true
                        },
                        axisLabel: {
                            textStyle: {
                                fontSize: 16
                            }
                        }
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        axisLabel: {
                            formatter: '{value}次',
                            textStyle: {
                                fontSize: 16
                            }
                        }
                    }
                ],

                series: [
                    { name: '巡更计划次数', type: 'bar' },
                    { name: '巡更实际次数', type: 'bar' },
                ],

            },
            options: []
        };


        for (var i = 0; i < this.state.schoolResult2.length; i++) {
            let schoolNameList = [];
            for(var j = 0;j < this.state.schoolName[i].length; j++){
                let arr = this.state.schoolName[i][j].split("\n");
                schoolNameList.push(arr[0]);
            }
            
            option.options.push({
                xAxis: {
                    data: sessionStorage.getItem("departmentType") == "教育局" ? this.state.schoolName[i]
                    : schoolNameList
                },
                series: [
                    {
                        name: '巡更计划次数',
                        type: 'bar',
                        data: this.state.schoolResult2[i],
                        barGap: '100%',
                        barMaxWidth: 25,
                        animation: false,
                        itemStyle:
                        {
                            color: 'rgb(255, 70, 131)',
                            normal: {
                                label: {
                                    show: true, //开启显示
                                    position: 'top', //在上方显示
                                    textStyle: { //数值样式
                                        color: 'black',
                                        fontSize: 14
                                    }
                                }
                            }
                        },
                        showBackground: true,
                        backgroundStyle: {
                            color: 'rgba(180, 180, 180, 0.2)'
                        },
                    },
                    {
                        name: '巡更实际次数',
                        type: 'bar',
                        data: this.state.schoolResult[i],
                        barGap: '100%',
                        barMaxWidth: 25,
                        animation: false,
                        itemStyle:
                            {
                                //color: 'rgb(255, 70, 131)',
                                //color: '#FFD700',
                                normal: {
                                    color: '#FFD700',
                                    label: {
                                        show: true, //开启显示
                                        position: 'top', //在上方显示
                                        textStyle: { //数值样式
                                            color: 'black',
                                            fontSize: 14
                                        }
                                    }
                                }
                            },
                        showBackground: true,
                        backgroundStyle: {
                            color: 'rgba(180, 180, 180, 0.2)'
                        },
                        // markLine: {
                        //     label: { formatter: '平均值: ' + this.state.chartAvg },
                        //     symbol: 'none',
                        //     data: [{
                        //         type: 'average',
                        //         name: '平均值',
                        //     }]
                        // },
            
                        markPoint: {
                            data: [
                                {
                                    type: 'max', name: '最大值'
                                }, {
                                    type: 'min', name: '最小值'
                                }
                            ]
                        }
                    }
                ]
            })
        }

    
        chart.setOption(option);
      
    }



    render() {
        let chartStyle = {
            height: '100%',
            width: '100%',
        };
        return (<div id={this.state.divId} style={chartStyle} />)
    }
}

//校巡更完成率排名
class eduPatrolRatesRank extends Component {
    constructor(props) {
        super(props);
        this.state = {
            alertVisible: false, //提示
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            tableLoading: true,
            filteredInfo: null,
            sortedInfo: null,
            searchData: [],
            schoolLevel: [],
            countyList: [],
            searchChartLoading: true,
            chartSearchData: {},
            chartSearchAvg: "",
            startTime: "",
            endTime: "",
            isSearch: false,
            departmentId: sessionStorage.getItem("departmentId")
        };
    }
    componentWillMount() {
    }
    componentDidMount() {
        this.refreshData();
    }
    getBeforeDayTime() {
        var time = (new Date()).getTime() - 24 * 60 * 60 * 1000;
        var beforeday = new Date(time); // 获取的是前一天日期

        beforeday = beforeday.getFullYear() + "-" + (beforeday.getMonth() + 1 > 9
            ? (beforeday.getMonth() + 1) : "0" + (beforeday.getMonth()+1)) + "-" + (beforeday.getDate() > 9
                ? (beforeday.getDate()) : "0" + (beforeday.getDate())); //字符串拼接转格式：例如2018-08-19
        
        return beforeday
    }
    getBeforeWeekTime() {
        var time = (new Date()).getTime() - 24 * 60 * 60 * 1000 * 7;
        var beforeweek = new Date(time); // 获取的是前一周日期

        beforeweek = beforeweek.getFullYear() + "-" + (beforeweek.getMonth() + 1 > 9
            ? (beforeweek.getMonth() + 1) : "0" + (beforeweek.getMonth() + 1)) + "-" + (beforeweek.getDate() > 9
                ? (beforeweek.getDate()) : "0" + (beforeweek.getDate())); //字符串拼接转格式：例如2018-08-19
        return beforeweek
    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        let columnData = [];
        let schoolLevel;
        var startTime = this.getBeforeWeekTime()
        var endTime = this.getBeforeDayTime()

        let departmentId = -sessionStorage.getItem("departmentId")

        getEduPatrolRatesRankApi(departmentId, schoolLevel, startTime, endTime)
            .then((res) => {
                res.data.edupatrolratesrankList.forEach((item, index) => {
                    columnData.push({
                        key: index + 1,
                        schoolname: item.schoolname,
                        patrolrates: item.patrolrates,
                        departmentName: item.departmentName
                    });
                });
                this.setState({
                    columnData: columnData,
                    startTime: startTime,
                    endTime: endTime,
                    tableLoading: false,
                    alertVisible: false,
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

            getEduPatrolRatesRankApi2(departmentId, schoolLevel, startTime, endTime)
            .then((res) => {
                if (res.data.serialList.length == 0) {
                    this.setState({
                        schoolResult: [],
                        schoolName: [],
                        serialList: [],
                        chartAvg: "",
                        tableLoading: false,
                        isSearch: false
                    });
                } else {
                    this.setState({
                        schoolResult: res.data.schoolResults,
                        schoolName: res.data.schoolNames,
                        serialList: res.data.serialList,
                        chartAvg: res.data.edupatrolratesavg,
                        searchChartLoading: false,
                        tableLoading: false,
                        alertVisible: false,
                        isSearch: true
                    });
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });




        this.getSchoolLevelByEduId(sessionStorage.getItem("departmentId"), 1)
        

        getDepartmentApi(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                this.setState({
                    countyList: res.data
                });
            }).catch((e) => {
                console.log(e);
            })
    }

    searchSubmit = (e) => {
        var schoolLevel;
        var departmentId;
        e.preventDefault();
        this.props.form.validateFields((err, values) => {

            if (values.deadline == undefined && values.schoolLevel == undefined) {
                message.error('请至少填写一项条件再进行搜索');
            } else {
                if (values.schoolLevel != undefined) {
                    schoolLevel = values.schoolLevel
                }
                if(!isNaN(values.county)){
                    departmentId = values.county
                }else{
                    departmentId = -parseInt(sessionStorage.getItem("departmentId"))
                }
                
                this.setState({
                    tableLoading: true
                });
                let columnData = [];
                getEduPatrolRatesRankApi(departmentId, schoolLevel, this.state.startTime, this.state.endTime)
                    .then((res) => {
                        res.data.edupatrolratesrankList.forEach((item, index) => {
                            columnData.push({
                                key: index + 1,
                                schoolname: item.schoolname,
                                patrolrates: item.patrolrates,
                                departmentName: item.departmentName
                            });
                        });
                        this.setState({
                            columnData: columnData,
                            tableLoading: false,
                            alertVisible: false,
                        });
                        if(values.average == 1){
                            let columnDataAvg = [];
                            let columnDataTemp = this.state.columnData;
                            let sum = 0;
                            for(let i = 0;i < columnDataTemp.length; i++){
                                sum += parseFloat(columnDataTemp[i].patrolrates);
                            }
                            let avg = sum / columnDataTemp.length;
                            let index = 1;
                            for(let i = 0;i < columnDataTemp.length;i ++){
                                if(parseFloat(columnDataTemp[i].patrolrates) <= avg){
                                    columnDataTemp[i].key = index++;
                                    columnDataAvg.push(columnDataTemp[i]);
                                }
                            }
                            this.setState({
                                columnData: columnDataAvg
                            })
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });
                getEduPatrolRatesRankApi2(departmentId, schoolLevel, this.state.startTime, this.state.endTime)
                    .then((res) => {
                        if (res.data.serialList.length == 0) {
                            this.setState({
                                schoolResult: [],
                                schoolName: [],
                                serialList: [],
                                chartAvg: "",
                                tableLoading: false,
                                isSearch: false
                            });
                        } else {
                            this.setState({
                                schoolResult: res.data.schoolResults,
                                schoolName: res.data.schoolNames,
                                serialList: res.data.serialList,
                                chartAvg: res.data.edupatrolratesavg,
                                searchChartLoading: false,
                                tableLoading: false,
                                alertVisible: false,
                                isSearch: true
                            });
                            if(values.average == 1){
                                let schoolResultAvg = [];
                                let schoolNameAvg = [];
                                let serialListAvg = [];
                                let t1 = [];
                                let t3 = [];
                                let count = 0;
                                for(let i = 0;i < this.state.schoolResult.length;i++){
                                    for(let j = 0;j < this.state.schoolResult[i].length;j++){
                                        if(parseFloat(this.state.schoolResult[i][j]) <= parseFloat(this.state.chartAvg)){
                                            if(count != 0 && count % 5 == 0){
                                                schoolResultAvg.push(t1);
                                                schoolNameAvg.push(t3);
                                                serialListAvg.push(parseInt((count-1) / 5) + 1);
                                                t1 = [];
                                                t3 = [];
                                            }
                                            t1.push(this.state.schoolResult[i][j]);
                                            t3.push(this.state.schoolName[i][j]);
                                            count++;
                                        }
                                    }
                                }
                                if(t1.length != 0){
                                    schoolResultAvg.push(t1);
                                    schoolNameAvg.push(t3);
                                    serialListAvg.push(parseInt((count-1) / 5) + 1);
                                }
                                this.setState({
                                    schoolResult: schoolResultAvg,
                                    schoolName: schoolNameAvg,
                                    serialList: serialListAvg,
                                })
                            }
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });



            }
        });
    }
    clearAll = () => {
        this.setState({
            filteredInfo: null,
            sortedInfo: null,
        });
    }
    handleChange = (pagination, filters, sorter) => {
        this.setState({
            filteredInfo: filters,
            sortedInfo: sorter,
        });
    }
    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
    }
    handleSearchReset = clearFilters => () => {
        clearFilters();
    }
    onRef = (ref) => {
        this.child = ref
    }

    searchReset = () => {
        this.props.form.resetFields();
    }

    setFullScreen(opts) {
        this.setState({
            fullScreenVisible: true,
        })
        let fullchart = echarts.init(document.getElementById('fullScreen'))
        fullchart.setOption(opts);
    }

    fullScreenCancel() {
        this.setState({
            fullScreenVisible: false,
        })
    }
    handleSelectTime = (value, dateString) => {
        if (dateString[0] != '' && dateString[1] != '') {
            this.setState({
                startTime: dateString[0],
                endTime: dateString[1],
            })
        }

    }

    handleChange2() {
        console.log("handleChange2()=========================")
    }

    getSchoolLevelByEduId(id, allType){
        getSchoolLevelByEduIdApi(id, allType)
            .then((res) => {
                this.setState({
                    schoolLevel: res.data,
                });

            })
    }

    render() {
        let schoolLevelOptions = [];
        schoolLevelOptions.push(<Option value={null} key={-1}>全部</Option>)
        if (this.state.schoolLevel.length != 0) {
            schoolLevelOptions.push(this.state.schoolLevel.map((d, index) =>
                <Option value={d.schoolLevel} key={index}>{d.schoolLevel}</Option>
            ))
        }
        let countyOptions = [];
        let name = sessionStorage.getItem("departmentName")
        let id = parseInt(sessionStorage.getItem("departmentId"))
        countyOptions.push(<Option value={-id} key={-id}>{name.substring(0, name.indexOf("市"))}全市</Option>)
        if(this.state.countyList.length != 0){
            countyOptions.push(this.state.countyList.map((item) =>
                <Option value={item.id} key={item.id}>{item.name}</Option>
            ))
        }
        const { getFieldDecorator, getFieldValue } = this.props.form;
        let { sortedInfo, filteredInfo } = this.state;
        sortedInfo = sortedInfo || {};
        filteredInfo = filteredInfo || {};
        const columnsSearch = [{
            title: "序号",
            dataIndex: "key",
            key: "key"
        }, {
            title: "学校",
            dataIndex: "schoolname",
            key: "schoolname",
            filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                <div className="custom-filter-dropdown">
                    <Input
                        ref={ele => this.searchInput = ele}
                        value={selectedKeys[0]}
                        onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                        onPressEnter={this.handleSearch(selectedKeys, confirm)}
                    />
                    <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                    <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                </div>
            ),
            filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
            onFilter: (value, record) => record.schoolname.toLowerCase().includes(value.toLowerCase()),
            onFilterDropdownVisibleChange: (visible) => {
                if (visible) {
                    setTimeout(() => {
                        this.searchInput.focus();
                    });
                }
            }
        }, 
        sessionStorage.getItem("departmentType") == "教育局" ? 
        {
            title: "区县",
            dataIndex: "departmentName",
            key: "departmentName"
        }:{}, {
            title: "巡更完成率(%)",
            dataIndex: "patrolrates",
            key: "patrolrates",
            sorter: (a, b) => a.patrolrates - b.patrolrates,
            sortDirections: ['descend', 'ascend'],

        },
        {
            title: '详情',
            dataIndex: 'action',
            key: 'action',
            render: (text, record) => {
                //  console.log("============================", record)
                return (
                    <span>
                        <a
                            onClick={toSchoolUrl.bind(this, record)}
                            // href={this.stahoolUrl}   
                            target="_blank"
                        >
                            查看详情
                        </a>
                        {/* <Button onClick={this.toSchoolUrl.bind(this, record)}> 查看详情</Button> */}
                    </span>
                )
            }
        }]
        let labelCol = {
            sm: { span: 6 },
            xl: { span: 6 },
            xxl: { span: 5 },
        };

        let wrapperCol = {
            sm: { span: 18 },
            xl: { span: 18 },
            xxl: { span: 19 },
        };

        // Excel头部标题
        const header = [
            {
                title: '序号',
                dataIndex: 'key',
                key: 'key',
            }, {
                title: '学校',
                dataIndex: 'schoolname',
                key: 'schoolname',
            }, {
                title: '区县',
                dataIndex: 'departmentName',
                key: 'departmentName',
            }, {
                title: '巡更完成率(%)',
                dataIndex: 'patrolrates',
                key: 'patrolrates',
            }
        ]


        return (
            <div style={{ marginBottom: 16 }}>
                <Form style={{
                    padding: '12px',
                    backgroundColor: '#fafafa',
                    borderRadius: 8,
                    marginBottom: 16,
                }}
                    layout="inline"
                    onSubmit={this.searchSubmit}>
                    <Row>
                        <Col span={8}>
                            <FormItem
                                label="截止日期"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("deadline", {
                                    rules: [{
                                        type: 'array',
                                        required: false,
                                    }],
                                    initialValue: [ // 核心代码
                                        moment(this.getBeforeWeekTime(), dateFormat),
                                        moment(this.getBeforeDayTime(), dateFormat),
                                      ],
                                })(
                                    <RangePicker
                                        style={{ width: '100%' }}
                                        format="YYYY-MM-DD"
                                        onChange={this.handleSelectTime} />
                                )}
                            </FormItem>
                        </Col>
                        {sessionStorage.getItem("departmentType") == "教育局" ? (
                            <Col span={5}>
                            <FormItem
                                label="区县"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("county", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请选择区县"
                                        onSelect = {(e) => {
                                            if(e < 0){
                                                this.getSchoolLevelByEduId(parseInt(sessionStorage.getItem("departmentId")), 1)
                                            }else {
                                                this.getSchoolLevelByEduId(e, 0)
                                            }
                                        }}>
                                        {countyOptions}
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        )
                        :null
                        }
                        <Col span={8}>
                            <FormItem
                                label="学校类型"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("schoolLevel", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请选择学校类型">
                                        {schoolLevelOptions}
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8}>
                        <FormItem
                                label="数值"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("average", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请选择数值情况">
                                        <Option value={0} key={0}>所有</Option>
                                        <Option value={1} key={1}>低于平均值</Option>
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        <Col>
                            <FormItem
                                style={{ float: 'right' }}>
                                <Button type="primary" htmlType="submit">搜索</Button>
                                <Button style={{ marginLeft: 8 }} onClick={this.searchReset}>清空</Button>
                                <Button type="primary" style={{ marginLeft: 8 }} onClick={() =>  {
                                    exportExcel(header, this.state.columnData, "学校巡更完成率排名.xlsx")
                                    }}>导出Excel
                                </Button>  
                            </FormItem>
                        </Col>
                    </Row>
                </Form>
                <div>
                    {
                        this.state.isSearch ?
                            (
                                <div style={{
                                    marginBottom: 16,
                                    padding: 16,
                                    width: '100%',
                                    height: 350,
                                    border: '1px solid',
                                    borderColor: '#f5f5f5'
                                }}>
                                    <Skeleton loading={this.state.searchChartLoading} active>
                                        <ChartSearchPatrolRates
                                            that={this}
                                            schoolName={this.state.schoolName}
                                            schoolResult={this.state.schoolResult}
                                            serialList={this.state.serialList}
                                            chartAvg={this.state.chartAvg}
                                            divId={'chartSearch'} />
                                    </Skeleton>
                                </div>
                            ) : null
                    }
                    {
                        this.state.isSearch ? 
                        (
                            <Alert
                            message="学校巡更完成率说明"
                            description={"学校巡更完成率=在统计时间范围内，该学校实际巡更打卡点位数/计划完成打卡点位数"}
                            type="info"
                            showIcon/>
                        ) : null
                    }
                    <Table
                        dataSource={this.state.columnData}
                        columns={columnsSearch}
                        loading={this.state.tableLoading}
                        locale={{ emptyText: '暂无数据' }}
                        onChange={this.handleChange2}
                        rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                        pagination={{  //分页
                            total: this.state.searchData.length, //数据总数量
                            defaultPageSize: 10, //默认显示几条一页
                            //pageSize: 10,
                            showTotal: function (total) {  //设置显示一共几条数据
                                return '共 ' + total + ' 条数据';
                            },
                            showSizeChanger: true,
                            showQuickJumper: true,
                            pageSizeOptions: [5, 10, 20, 30]
                        }} />
                </div>
            </div>
        );
    }
}
const EduPatrolRatesRank = Form.create()(eduPatrolRatesRank);

//校巡更完成率排名柱状图
class ChartSearchPatrolRates extends Component {
    constructor(props) {
        super(props);
        this.state = {
            schoolResult: props.schoolResult || [],
            //schoolResult: [[1281.0, 600.0, 72.0, 87, 94], [63.0, 0.0, -1.5, 98, 391]],
            schoolName: props.schoolName || [],
            //schoolName: [[" 丰惠镇中心幼儿园", "第二实验幼儿园盛丰园区", "第一实验幼儿园和润花园区", "第一实验幼儿园新上海园区", "梯度中学"], ["第一实验幼儿园新上海园区", "梯度中学", "上浦镇中心幼儿园", "第一实验幼儿园新上海园区", "梯度中学"]],
            serialList: props.serialList || [],
            //serialList: ["1", "2"],
            that: props.that,
            currentIndex: 0,
            divId: props.divId,
            data1: 0,
            schoolNamePart: [],
            chartAvg: props.chartAvg
        };

    }

    componentWillReceiveProps(props) {

        if (JSON.stringify(props.schoolName) != JSON.stringify(this.state.schoolName) && props.serialList.length > 0) {
            this.setState({
                that: props.that,
                schoolResult: props.schoolResult,
                schoolName: props.schoolName,
                serialList: props.serialList,
                chartAvg: props.chartAvg
            }, () => {
                this.drawChart()
            })
        }
    }

    componentDidMount() {
        let optionData = [];
        if (this.state.schoolName.length != 0) {
            this.drawChart();
        }
    }




    drawChart() {

        let optionData = [];

        let chart = echarts.init(document.getElementById('chartSearch'));
        let option = {

            baseOption: {
                timeline: {
                    axisType: 'category',
                    triggerEvent: true,
                    playInterval: 1000,
                    data: this.state.serialList
                },
                title: {
                    text: '学校巡更完成率排名',
                    left: 'center',
                    top: '10px',
                    subtext:'平均值: ' + this.state.chartAvg +'%',
                    subtextStyle: {
                        fontSize: 16
                    }
                },
                color: ['#3398DB'],
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                        type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                    }
                },
                toolbox: {
                    show: true,
                    feature: {
                        dataZoom: {
                            yAxisIndex: 'none'
                        },
                        dataView: { readOnly: false },
                        magicType: { type: ['line', 'bar'] },
                        restore: {},
                        saveAsImage: {}
                    }
                },
                grid: {
                    left: '5%',
                    right: '5%',
                    bottom: '50px',
                    top: '90px',
                    containLabel: true
                },
                xAxis: [
                    {
                        type: 'category',
                        data: this.state.schoolNamePart,
                        axisTick: {
                            alignWithLabel: true
                        },
                        axisLabel: {
                            textStyle: {
                                fontSize: 16
                            }
                        }
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        axisLabel: {
                            formatter: '{value}%',
                            textStyle: {
                                fontSize: 16
                            }
                        }
                    }
                ],

                series: [
                    { name: '巡更次数', type: 'bar' },
                ],

            },
            options: []
        };


        for (var i = 0; i < this.state.schoolResult.length; i++) {
            let schoolNameList = [];
            for(var j = 0;j < this.state.schoolName[i].length; j++){
                let arr = this.state.schoolName[i][j].split("\n");
                schoolNameList.push(arr[0]);
            }
            
            option.options.push({
                xAxis: {
                    data: sessionStorage.getItem("departmentType") == "教育局" ? this.state.schoolName[i]
                    : schoolNameList
                },
                series: [                
                    {
                        name: '巡更完成率',
                        type: 'bar',
                        data: this.state.schoolResult[i],
                        barGap: '100%',
                        barMaxWidth: 25,
                        animation: false,
                        itemStyle:
                            {
                                color: 'rgb(255, 70, 131)',
                                //color: '#FFD700',
                                normal: {
                                   // color: '#FFD700',
                                    label: {
                                        show: true, //开启显示
                                        position: 'top', //在上方显示
                                        textStyle: { //数值样式
                                            color: 'black',
                                            fontSize: 14
                                        }
                                    }
                                }
                            },
                        showBackground: true,
                        backgroundStyle: {
                            color: 'rgba(180, 180, 180, 0.2)'
                        },
                        // markLine: {
                        //     label: { formatter: '平均值: ' + this.state.chartAvg },
                        //     symbol: 'none',
                        //     data: [{
                        //         type: 'average',
                        //         name: '平均值',
                        //     }]
                        // },
            
                        markPoint: {
                            data: [
                                {
                                    type: 'max', name: '最大值'
                                }, {
                                    type: 'min', name: '最小值'
                                }
                            ]
                        }
                    }
                ]
            })
        }

    
        chart.setOption(option);
    

    }




    render() {
        let chartStyle = {
            height: '100%',
            width: '100%',
        };
        return (<div id={this.state.divId} style={chartStyle} />)
    }
}

//校巡更积分排名
class eduPatrolPointsRank extends Component {
    constructor(props) {
        super(props);
        this.state = {
            alertVisible: false, //提示
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            tableLoading: true,
            filteredInfo: null,
            sortedInfo: null,
            searchData: [],
            schoolLevel: [],
            countyList: [],
            searchChartLoading: true,
            chartSearchData: {},
            chartSearchAvg: "",
            startTime: "",
            endTime: "",
            isSearch: false,
            departmentId: sessionStorage.getItem("departmentId")
        };
    }
    componentWillMount() {
    }
    componentDidMount() {
        this.refreshData();
    }
    getBeforeDayTime() {
        var time = (new Date()).getTime() - 24 * 60 * 60 * 1000;
        var beforeday = new Date(time); // 获取的是前一天日期

        beforeday = beforeday.getFullYear() + "-" + (beforeday.getMonth() + 1 > 9
            ? (beforeday.getMonth() + 1) : "0" + (beforeday.getMonth()+1)) + "-" + (beforeday.getDate() > 9
                ? (beforeday.getDate()) : "0" + (beforeday.getDate())); //字符串拼接转格式：例如2018-08-19
        
        return beforeday
    }
    getBeforeWeekTime() {
        var time = (new Date()).getTime() - 24 * 60 * 60 * 1000 * 7;
        var beforeweek = new Date(time); // 获取的是前一周日期

        beforeweek = beforeweek.getFullYear() + "-" + (beforeweek.getMonth() + 1 > 9
            ? (beforeweek.getMonth() + 1) : "0" + (beforeweek.getMonth() + 1)) + "-" + (beforeweek.getDate() > 9
                ? (beforeweek.getDate()) : "0" + (beforeweek.getDate())); //字符串拼接转格式：例如2018-08-19
        return beforeweek
    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        let columnData = [];
        let schoolLevel;
        var startTime = this.getBeforeWeekTime()
        var endTime = this.getBeforeDayTime()

        let departmentId = -sessionStorage.getItem("departmentId")

        getEduPatrolPointsRankApi(departmentId, schoolLevel, startTime, endTime)
            .then((res) => {
                res.data.edupatrolpointsrankList.forEach((item, index) => {
                    columnData.push({
                        key: index + 1,
                        schoolname: item.schoolname,
                        patrolpoints: item.patrolpoints,
                        departmentName: item.departmentName,
                        patrolnum: item.patrolnum,
                        patrolrates: item.patrolrates
                    });
                });
                this.setState({
                    columnData: columnData,
                    startTime: startTime,
                    endTime: endTime,
                    tableLoading: false,
                    alertVisible: false,
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });


            getEduPatrolPointsRankApi2(departmentId, schoolLevel, startTime, endTime)
            .then((res) => {
                if (res.data.serialList.length == 0) {
                    this.setState({
                        schoolResult: [],
                        schoolName: [],
                        serialList: [],
                        chartAvg: "",
                        tableLoading: false,
                        isSearch: false
                    });
                } else {
                    this.setState({
                        schoolResult: res.data.schoolResults,
                        schoolName: res.data.schoolNames,
                        serialList: res.data.serialList,
                        chartAvg: res.data.edupatrolpointsavg,
                        searchChartLoading: false,
                        tableLoading: false,
                        alertVisible: false,
                        isSearch: true
                    });
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });


        this.getSchoolLevelByEduId(sessionStorage.getItem("departmentId"), 1)
    

        getDepartmentApi(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                this.setState({
                    countyList: res.data
                });
            }).catch((e) => {
                console.log(e);
            })
    }

    searchSubmit = (e) => {
        var schoolLevel;
        var departmentId;
        e.preventDefault();
        this.props.form.validateFields((err, values) => {

            if (values.deadline == undefined && values.schoolLevel == undefined) {
                message.error('请至少填写一项条件再进行搜索');
            } else {
                if (values.schoolLevel != undefined) {
                    schoolLevel = values.schoolLevel
                }
                if(!isNaN(values.county)){
                    departmentId = values.county
                }else{
                    departmentId = -parseInt(sessionStorage.getItem("departmentId"))
                }
                this.setState({
                    tableLoading: true
                });
                let columnData = [];
                getEduPatrolPointsRankApi(departmentId, schoolLevel, this.state.startTime, this.state.endTime)
                    .then((res) => {
                        res.data.edupatrolpointsrankList.forEach((item, index) => {
                            columnData.push({
                                key: index + 1,
                                schoolname: item.schoolname,
                                patrolpoints: item.patrolpoints,
                                departmentName: item.departmentName,
                                patrolnum: item.patrolnum,
                                patrolrates: item.patrolrates
                            });
                        });
                        this.setState({
                            columnData: columnData,
                            tableLoading: false,
                            alertVisible: false,
                        });
                        if(values.average == 1){
                            let columnDataAvg = [];
                            let columnDataTemp = this.state.columnData;
                            let sum = 0;
                            for(let i = 0;i < columnDataTemp.length; i++){
                                sum += parseFloat(columnDataTemp[i].patrolpoints);
                            }
                            let avg = sum / columnDataTemp.length;
                            let index = 1;
                            for(let i = 0;i < columnDataTemp.length;i ++){
                                if(parseFloat(columnDataTemp[i].patrolpoints) <= avg){
                                    columnDataTemp[i].key = index++;
                                    columnDataAvg.push(columnDataTemp[i]);
                                }
                            }
                            this.setState({
                                columnData: columnDataAvg
                            })
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });
                getEduPatrolPointsRankApi2(departmentId, schoolLevel, this.state.startTime, this.state.endTime)
                    .then((res) => {
                        if (res.data.serialList.length == 0) {
                            this.setState({
                                schoolResult: [],
                                schoolName: [],
                                serialList: [],
                                chartAvg: "",
                                tableLoading: false,
                                isSearch: false
                            });
                        } else {
                            this.setState({
                                schoolResult: res.data.schoolResults,
                                schoolName: res.data.schoolNames,
                                serialList: res.data.serialList,
                                chartAvg: res.data.edupatrolpointsavg,
                                searchChartLoading: false,
                                tableLoading: false,
                                alertVisible: false,
                                isSearch: true
                            });
                            if(values.average == 1){
                                let schoolResultAvg = [];
                                let schoolNameAvg = [];
                                let serialListAvg = [];
                                let t1 = [];
                                let t3 = [];
                                let count = 0;
                                for(let i = 0;i < this.state.schoolResult.length;i++){
                                    for(let j = 0;j < this.state.schoolResult[i].length;j++){
                                        if(parseFloat(this.state.schoolResult[i][j]) <= parseFloat(this.state.chartAvg)){
                                            if(count != 0 && count % 5 == 0){
                                                schoolResultAvg.push(t1);
                                                schoolNameAvg.push(t3);
                                                serialListAvg.push(parseInt((count-1) / 5) + 1);
                                                t1 = [];
                                                t3 = [];
                                            }
                                            t1.push(this.state.schoolResult[i][j]);
                                            t3.push(this.state.schoolName[i][j]);
                                            count++;
                                        }
                                    }
                                }
                                if(t1.length != 0){
                                    schoolResultAvg.push(t1);
                                    schoolNameAvg.push(t3);
                                    serialListAvg.push(parseInt((count-1) / 5) + 1);
                                }
                                this.setState({
                                    schoolResult: schoolResultAvg,
                                    schoolName: schoolNameAvg,
                                    serialList: serialListAvg,
                                })
                            }
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });



            }
        });
    }
    clearAll = () => {
        this.setState({
            filteredInfo: null,
            sortedInfo: null,
        });
    }
    handleChange = (pagination, filters, sorter) => {
        this.setState({
            filteredInfo: filters,
            sortedInfo: sorter,
        });
    }
    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
    }
    handleSearchReset = clearFilters => () => {
        clearFilters();
    }
    onRef = (ref) => {
        this.child = ref
    }

    searchReset = () => {
        this.props.form.resetFields();
    }

    setFullScreen(opts) {
        this.setState({
            fullScreenVisible: true,
        })
        let fullchart = echarts.init(document.getElementById('fullScreen'))
        fullchart.setOption(opts);
    }

    fullScreenCancel() {
        this.setState({
            fullScreenVisible: false,
        })
    }
    handleSelectTime = (value, dateString) => {
        if (dateString[0] != '' && dateString[1] != '') {
            this.setState({
                startTime: dateString[0],
                endTime: dateString[1],
            })
        }

    }

    handleChange2() {
        console.log("handleChange2()=========================")
    }

    getSchoolLevelByEduId(id, allType){
        getSchoolLevelByEduIdApi(id, allType)
            .then((res) => {
                this.setState({
                    schoolLevel: res.data,
                });

            })
    }

    render() {
        let schoolLevelOptions = [];
        schoolLevelOptions.push(<Option value={null} key={-1}>全部</Option>)
        if (this.state.schoolLevel.length != 0) {
            schoolLevelOptions.push(this.state.schoolLevel.map((d, index) =>
                <Option value={d.schoolLevel} key={index}>{d.schoolLevel}</Option>
            ))
        }
        let countyOptions = [];
        let name = sessionStorage.getItem("departmentName")
        let id = parseInt(sessionStorage.getItem("departmentId"))
        countyOptions.push(<Option value={-id} key={-id}>{name.substring(0, name.indexOf("市"))}全市</Option>)
        if(this.state.countyList.length != 0){
            countyOptions.push(this.state.countyList.map((item) =>
                <Option value={item.id} key={item.id}>{item.name}</Option>
            ))
        }
        const { getFieldDecorator, getFieldValue } = this.props.form;
        let { sortedInfo, filteredInfo } = this.state;
        sortedInfo = sortedInfo || {};
        filteredInfo = filteredInfo || {};
        const columnsSearch = [{
            title: "序号",
            dataIndex: "key",
            key: "key"
        }, {
            title: "学校",
            dataIndex: "schoolname",
            key: "schoolname",
            filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                <div className="custom-filter-dropdown">
                    <Input
                        ref={ele => this.searchInput = ele}
                        value={selectedKeys[0]}
                        onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                        onPressEnter={this.handleSearch(selectedKeys, confirm)}
                    />
                    <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                    <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                </div>
            ),
            filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
            onFilter: (value, record) => record.schoolname.toLowerCase().includes(value.toLowerCase()),
            onFilterDropdownVisibleChange: (visible) => {
                if (visible) {
                    setTimeout(() => {
                        this.searchInput.focus();
                    });
                }
            }
        },
        sessionStorage.getItem("departmentType") == "教育局" ? 
        {
            title: "区县",
            dataIndex: "departmentName",
            key: "departmentName"
        }:{}, {
            title: "巡更次数",
            dataIndex: "patrolnum",
            key: "patrolnum",

        }, {
            title: "巡更完成率(%)",
            dataIndex: "patrolrates",
            key: "patrolrates",

        }, {
            title: "巡更积分",
            dataIndex: "patrolpoints",
            key: "patrolpoints",
            sorter: (a, b) => a.patrolpoints - b.patrolpoints,
            sortDirections: ['descend', 'ascend'],

        },
        {
            title: '详情',
            dataIndex: 'action',
            key: 'action',
            render: (text, record) => {
                //  console.log("============================", record)
                return (
                    <span>
                        <a
                            onClick={toSchoolUrl.bind(this, record)}
                            // href={this.stahoolUrl}   
                            target="_blank"
                        >
                            查看详情
                        </a>
                        {/* <Button onClick={this.toSchoolUrl.bind(this, record)}> 查看详情</Button> */}
                    </span>
                )
            }
        }]
        let labelCol = {
            sm: { span: 6 },
            xl: { span: 6 },
            xxl: { span: 5 },
        };

        let wrapperCol = {
            sm: { span: 18 },
            xl: { span: 18 },
            xxl: { span: 19 },
        };

        // Excel头部标题
        const header = [
            {
                title: '序号',
                dataIndex: 'key',
                key: 'key',
            }, {
                title: '学校',
                dataIndex: 'schoolname',
                key: 'schoolname',
            }, {
                title: '区县',
                dataIndex: 'departmentName',
                key: 'departmentName',
            }, {
                title: "巡更次数",
                dataIndex: "patrolnum",
                key: "patrolnum",
    
            }, {
                title: "巡更完成率(%)",
                dataIndex: "patrolrates",
                key: "patrolrates",
    
            }, {
                title: '巡更积分(分)',
                dataIndex: 'patrolpoints',
                key: 'patrolpoints',
            }
        ]


        return (
            <div style={{ marginBottom: 16 }}>
                <Form style={{
                    padding: '12px',
                    backgroundColor: '#fafafa',
                    borderRadius: 8,
                    marginBottom: 16,
                }}
                    layout="inline"
                    onSubmit={this.searchSubmit}>
                    <Row>
                        <Col span={8}>
                            <FormItem
                                label="截止日期"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("deadline", {
                                    rules: [{
                                        type: 'array',
                                        required: false,
                                    }],
                                    initialValue: [ // 核心代码
                                        moment(this.getBeforeWeekTime(), dateFormat),
                                        moment(this.getBeforeDayTime(), dateFormat),
                                      ],
                                })(
                                    <RangePicker
                                        style={{ width: '100%' }}
                                        format="YYYY-MM-DD"
                                        onChange={this.handleSelectTime} />
                                )}
                            </FormItem>
                        </Col>
                        {sessionStorage.getItem("departmentType") == "教育局" ? (
                            <Col span={5}>
                            <FormItem
                                label="区县"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("county", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请选择区县"
                                        onSelect = {(e) => {
                                            if(e < 0){
                                                this.getSchoolLevelByEduId(parseInt(sessionStorage.getItem("departmentId")), 1)
                                            }else {
                                                this.getSchoolLevelByEduId(e, 0)
                                            }
                                        }}>
                                        {countyOptions}
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        )
                        :null
                        }
                        <Col span={8}>
                            <FormItem
                                label="学校类型"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("schoolLevel", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请选择学校类型">
                                        {schoolLevelOptions}
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8}>
                        <FormItem
                                label="数值"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("average", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请选择数值情况">
                                        <Option value={0} key={0}>所有</Option>
                                        <Option value={1} key={1}>低于平均值</Option>
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        <Col>
                            <FormItem
                                style={{ float: 'right' }}>
                                <Button type="primary" htmlType="submit">搜索</Button>
                                <Button style={{ marginLeft: 8 }} onClick={this.searchReset}>清空</Button>
                                <Button type="primary" style={{ marginLeft: 8 }} onClick={() =>  {
                                    exportExcel(header, this.state.columnData, "学校巡更积分排名.xlsx")
                                    }}>导出Excel
                                </Button> 
                            </FormItem>
                        </Col>
                    </Row>
                </Form>
                <div>
                    {
                        this.state.isSearch ?
                            (
                                <div style={{
                                    marginBottom: 16,
                                    padding: 16,
                                    width: '100%',
                                    height: 350,
                                    border: '1px solid',
                                    borderColor: '#f5f5f5'
                                }}>
                                    <Skeleton loading={this.state.searchChartLoading} active>
                                        <ChartSearchPatrolPoints
                                            that={this}
                                            schoolName={this.state.schoolName}
                                            schoolResult={this.state.schoolResult}
                                            serialList={this.state.serialList}
                                            chartAvg={this.state.chartAvg}
                                            divId={'chartSearch'} />
                                    </Skeleton>
                                </div>
                            ) : null
                    }
                    {
                        this.state.isSearch ? 
                        (
                            <Alert
                            message="学校巡更积分说明"
                            description={"学校巡更积分=在统计时间范围内，该学校巡更次数*巡更完成率"}
                            type="info"
                            showIcon/>
                        ) : null
                    }
                    <Table
                        dataSource={this.state.columnData}
                        columns={columnsSearch}
                        loading={this.state.tableLoading}
                        locale={{ emptyText: '暂无数据' }}
                        onChange={this.handleChange2}
                        rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                        pagination={{  //分页
                            total: this.state.searchData.length, //数据总数量
                            defaultPageSize: 10, //默认显示几条一页
                            //pageSize: 10,
                            showTotal: function (total) {  //设置显示一共几条数据
                                return '共 ' + total + ' 条数据';
                            },
                            showSizeChanger: true,
                            showQuickJumper: true,
                            pageSizeOptions: [5, 10, 20, 30]
                        }} />
                </div>
            </div>
        );
    }
}
const EduPatrolPointsRank = Form.create()(eduPatrolPointsRank);

//校巡更积分排名柱状图
class ChartSearchPatrolPoints extends Component {
    constructor(props) {
        super(props);
        this.state = {
            schoolResult: props.schoolResult || [],
            //schoolResult: [[1281.0, 600.0, 72.0, 87, 94], [63.0, 0.0, -1.5, 98, 391]],
            schoolName: props.schoolName || [],
            //schoolName: [[" 丰惠镇中心幼儿园", "第二实验幼儿园盛丰园区", "第一实验幼儿园和润花园区", "第一实验幼儿园新上海园区", "梯度中学"], ["第一实验幼儿园新上海园区", "梯度中学", "上浦镇中心幼儿园", "第一实验幼儿园新上海园区", "梯度中学"]],
            serialList: props.serialList || [],
            //serialList: ["1", "2"],
            that: props.that,
            currentIndex: 0,
            divId: props.divId,
            data1: 0,
            schoolNamePart: [],
            chartAvg: props.chartAvg
        };

    }

    componentWillReceiveProps(props) {

        if (JSON.stringify(props.schoolName) != JSON.stringify(this.state.schoolName) && props.serialList.length > 0) {
            this.setState({
                that: props.that,
                schoolResult: props.schoolResult,
                schoolName: props.schoolName,
                serialList: props.serialList,
                chartAvg: props.chartAvg
            }, () => {
                this.drawChart()
            })
        }
    }

    componentDidMount() {
        let optionData = [];
        if (this.state.schoolName.length != 0) {
            this.drawChart();
        }
    }




    drawChart() {

        let optionData = [];

        let chart = echarts.init(document.getElementById('chartSearch'));
        let option = {

            baseOption: {
                timeline: {
                    axisType: 'category',
                    triggerEvent: true,
                    playInterval: 1000,
                    data: this.state.serialList
                },
                title: {
                    text: '学校巡更积分排名',
                    left: 'center',
                    top: '10px',
                    subtext:'平均值: ' + this.state.chartAvg +'分',
                    subtextStyle: {
                        fontSize: 16
                    }
                },
                color: ['#3398DB'],
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                        type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                    }
                },
                toolbox: {
                    show: true,
                    feature: {
                        dataZoom: {
                            yAxisIndex: 'none'
                        },
                        dataView: { readOnly: false },
                        magicType: { type: ['line', 'bar'] },
                        restore: {},
                        saveAsImage: {}
                    }
                },
                grid: {
                    left: '5%',
                    right: '5%',
                    bottom: '50px',
                    top: '90px',
                    containLabel: true
                },
                xAxis: [
                    {
                        type: 'category',
                        data: this.state.schoolNamePart,
                        axisTick: {
                            alignWithLabel: true
                        },
                        axisLabel: {
                            textStyle: {
                                fontSize: 16
                            }
                        }
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        axisLabel: {
                            formatter: '{value}分',
                            textStyle: {
                                fontSize: 16
                            }
                        }
                    }
                ],

                series: [
                    { name: '巡更积分', type: 'bar' },
                ],

            },
            options:[]
        };

        
        for (var i = 0; i < this.state.schoolResult.length; i++) {
            let schoolNameList = [];
            for(var j = 0;j < this.state.schoolName[i].length; j++){
                let arr = this.state.schoolName[i][j].split("\n");
                schoolNameList.push(arr[0]);
            }
            
            option.options.push({
                xAxis: {
                    data: sessionStorage.getItem("departmentType") == "教育局" ? this.state.schoolName[i]
                    : schoolNameList
                },
                series: [                
                    {
                        name: '巡更积分',
                        type: 'bar',
                        data: this.state.schoolResult[i],
                        barGap: '100%',
                        barMaxWidth: 25,
                        animation: false,
                        itemStyle:
                            {
                                color: 'rgb(255, 70, 131)',
                                //color: '#FFD700',
                                normal: {
                                   // color: '#FFD700',
                                    label: {
                                        show: true, //开启显示
                                        position: 'top', //在上方显示
                                        textStyle: { //数值样式
                                            color: 'black',
                                            fontSize: 14
                                        }
                                    }
                                }
                            },
                        showBackground: true,
                        backgroundStyle: {
                            color: 'rgba(180, 180, 180, 0.2)'
                        },
                        // markLine: {
                        //     label: { formatter: '平均值: ' + this.state.chartAvg },
                        //     symbol: 'none',
                        //     data: [{
                        //         type: 'average',
                        //         name: '平均值',
                        //     }]
                        // },
            
                        markPoint: {
                            data: [
                                {
                                    type: 'max', name: '最大值'
                                }, {
                                    type: 'min', name: '最小值'
                                }
                            ]
                        }
                    }
                ]
            })
        }

        chart.setOption(option);
       


    }


   


    render() {
        let chartStyle = {
            height: '100%',
            width: '100%',
        };
        return (<div id={this.state.divId} style={chartStyle} />)
    }
}

//校隐患次数排名
class eduDangerNumRank extends Component {
    constructor(props) {
        super(props);
        this.state = {
            alertVisible: false, //提示
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            tableLoading: true,
            filteredInfo: null,
            sortedInfo: null,
            searchData: [],
            schoolLevel: [],
            countyList: [],
            searchChartLoading: true,
            chartSearchData: {},
            chartSearchAvg: "",
            startTime: "",
            endTime: "",
            isSearch: false,
            departmentId: sessionStorage.getItem("departmentId"),
            
            
        };
    }
    componentWillMount() {
    }
    componentDidMount() {
        this.refreshData();
    }
    getBeforeDayTime() {
        var time = (new Date()).getTime() - 24 * 60 * 60 * 1000;
        var beforeday = new Date(time); // 获取的是前一天日期

        beforeday = beforeday.getFullYear() + "-" + (beforeday.getMonth() + 1 > 9
            ? (beforeday.getMonth() + 1) : "0" + (beforeday.getMonth()+1)) + "-" + (beforeday.getDate() > 9
                ? (beforeday.getDate()) : "0" + (beforeday.getDate())); //字符串拼接转格式：例如2018-08-19
        
        return beforeday
    }
    getBeforeWeekTime() {
        var time = (new Date()).getTime() - 24 * 60 * 60 * 1000 * 7;
        var beforeweek = new Date(time); // 获取的是前一周日期

        beforeweek = beforeweek.getFullYear() + "-" + (beforeweek.getMonth() + 1 > 9
            ? (beforeweek.getMonth() + 1) : "0" + (beforeweek.getMonth() + 1)) + "-" + (beforeweek.getDate() > 9
                ? (beforeweek.getDate()) : "0" + (beforeweek.getDate())); //字符串拼接转格式：例如2018-08-19
        return beforeweek
    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        let columnData = [];
        let schoolLevel;
        var startTime = this.getBeforeWeekTime()
        var endTime = this.getBeforeDayTime()

        let departmentId = -sessionStorage.getItem("departmentId")

        getEduDangerNumRankApi(departmentId, schoolLevel, startTime, endTime)
            .then((res) => {
                res.data.edudangernumrankList.forEach((item, index) => {
                    columnData.push({
                        key: index + 1,
                        schoolname: item.schoolname,
                        dangernum: item.dangernum,
                        dangerdealnum: item.dangerdealnum,
                        departmentName: item.departmentName,
                        schoolId: item.departmentId
                    });
                });
                this.setState({
                    columnData: columnData,
                    startTime: startTime,
                    endTime: endTime,
                    tableLoading: false,
                    alertVisible: false,
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });


            getEduDangerNumRankApi2(departmentId, schoolLevel, startTime, endTime)
            .then((res) => {
                if (res.data.serialList.length == 0) {
                    this.setState({
                        schoolResult: [],
                        schoolName: [],
                        serialList: [],
                        chartAvg: "",
                        tableLoading: false,
                        isSearch: false
                    });
                } else {
                    this.setState({
                        schoolResult: res.data.schoolResults,
                        schoolResult2: res.data.schoolResults2,
                        schoolName: res.data.schoolNames,
                        serialList: res.data.serialList,
                        chartAvg: res.data.edudangernumavg,
                        alldangernum: res.data.alldangernum,
                        alldangerdealnum: res.data.alldangerdealnum,
                        searchChartLoading: false,
                        tableLoading: false,
                        alertVisible: false,
                        isSearch: true
                    });
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

        this.getSchoolLevelByEduId(sessionStorage.getItem("departmentId"), 1)
    

        getDepartmentApi(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                this.setState({
                    countyList: res.data
                });
            }).catch((e) => {
                console.log(e);
            })
    }

    searchSubmit = (e) => {
        var schoolLevel;
        var departmentId;
        e.preventDefault();
        this.props.form.validateFields((err, values) => {

            if (values.deadline == undefined && values.schoolLevel == undefined) {
                message.error('请至少填写一项条件再进行搜索');
            } else {
                if (values.schoolLevel != undefined) {
                    schoolLevel = values.schoolLevel
                }
                if(!isNaN(values.county)){
                    departmentId = values.county
                }else{
                    departmentId = -parseInt(sessionStorage.getItem("departmentId"))
                }
                this.setState({
                    tableLoading: true
                });
                let columnData = [];
                getEduDangerNumRankApi(departmentId, schoolLevel, this.state.startTime, this.state.endTime)
                    .then((res) => {
                        res.data.edudangernumrankList.forEach((item, index) => {
                            columnData.push({
                                key: index + 1,
                                schoolname: item.schoolname,
                                dangernum: item.dangernum,
                                dangerdealnum: item.dangerdealnum,
                                departmentName: item.departmentName,
                                schoolId: item.departmentId
                            });
                        });
                        this.setState({
                            columnData: columnData,
                            tableLoading: false,
                            alertVisible: false,
                        });
                        if(values.average == 1){
                            let columnDataAvg = [];
                            let columnDataTemp = this.state.columnData;
                            let sum = 0;
                            for(let i = 0;i < columnDataTemp.length; i++){
                                sum += columnDataTemp[i].dangernum;
                            }
                            let avg = sum / columnDataTemp.length;
                            let index = 1;
                            for(let i = 0;i < columnDataTemp.length;i ++){
                                if(columnDataTemp[i].dangernum <= avg){
                                    columnDataTemp[i].key = index++;
                                    columnDataAvg.push(columnDataTemp[i]);
                                }
                            }
                            this.setState({
                                columnData: columnDataAvg
                            })
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });
                getEduDangerNumRankApi2(departmentId, schoolLevel, this.state.startTime, this.state.endTime)
                    .then((res) => {
                        if (res.data.serialList.length == 0) {
                            this.setState({
                                schoolResult: [],
                                schoolName: [],
                                serialList: [],
                                chartAvg: "",
                                tableLoading: false,
                                isSearch: false
                            });
                        } else {
                            this.setState({
                                schoolResult: res.data.schoolResults,
                                schoolResult2: res.data.schoolResults2,
                                schoolName: res.data.schoolNames,
                                serialList: res.data.serialList,
                                chartAvg: res.data.edudangernumavg,
                                alldangernum: res.data.alldangernum,
                                alldangerdealnum: res.data.alldangerdealnum,
                                searchChartLoading: false,
                                tableLoading: false,
                                alertVisible: false,
                                isSearch: true
                            });
                            if(values.average == 1){
                                let schoolResultAvg = [];
                                let schoolNameAvg = [];
                                let serialListAvg = [];
                                let t1 = [];
                                let t3 = [];
                                let count = 0;
                                for(let i = 0;i < this.state.schoolResult.length;i++){
                                    for(let j = 0;j < this.state.schoolResult[i].length;j++){
                                        if(this.state.schoolResult[i][j] <= parseInt(this.state.chartAvg)){
                                            if(count != 0 && count % 5 == 0){
                                                schoolResultAvg.push(t1);
                                                schoolNameAvg.push(t3);
                                                serialListAvg.push(parseInt((count-1) / 5) + 1);
                                                t1 = [];
                                                t3 = [];
                                            }
                                            t1.push(this.state.schoolResult[i][j]);
                                            t3.push(this.state.schoolName[i][j]);
                                            count++;
                                        }
                                    }
                                }
                                if(t1.length != 0){
                                    schoolResultAvg.push(t1);
                                    schoolNameAvg.push(t3);
                                    serialListAvg.push(parseInt((count-1) / 5) + 1);
                                }
                                this.setState({
                                    schoolResult: schoolResultAvg,
                                    schoolName: schoolNameAvg,
                                    serialList: serialListAvg,
                                })
                            }
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });



            }
        });
    }
    handleDetailDrawerCancel() {
        this.setState({
            detailVisible: false,
            flag:false,
        })
    }
    handleDetailDrawerClick(){
        this.setState({
            flag:false,
        })
    }
    showDetailDrawer(schoolId){
         console.log('========划窗')
        this.setState({
            detailExist: true,
            detailVisible: true,
            currentSchoolId: schoolId,
            flag:true
        })
    }
    clearAll = () => {
        this.setState({
            filteredInfo: null,
            sortedInfo: null,
        });
    }
    handleChange = (pagination, filters, sorter) => {
        this.setState({
            filteredInfo: filters,
            sortedInfo: sorter,
        });
    }
    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
    }
    handleSearchReset = clearFilters => () => {
        clearFilters();
    }
    onRef = (ref) => {
        this.child = ref
    }

    searchReset = () => {
        this.props.form.resetFields();
    }

    setFullScreen(opts) {
        this.setState({
            fullScreenVisible: true,
        })
        let fullchart = echarts.init(document.getElementById('fullScreen'))
        fullchart.setOption(opts);
    }

    fullScreenCancel() {
        this.setState({
            fullScreenVisible: false,
        })
    }
    handleSelectTime = (value, dateString) => {
        console.log("test", value);
        console.log("test2", dateString);
        if (dateString[0] != '' && dateString[1] != '') {
            this.setState({
                startTime: dateString[0],
                endTime: dateString[1],
            })
        }

    }

    handleChange2() {
        console.log("handleChange2()=========================")
    }

    getSchoolLevelByEduId(id, allType){
        getSchoolLevelByEduIdApi(id, allType)
            .then((res) => {
                this.setState({
                    schoolLevel: res.data,
                });

            })
    }

    render() {
        let schoolLevelOptions = [];
        schoolLevelOptions.push(<Option value={null} key={-1}>全部</Option>)
        if (this.state.schoolLevel.length != 0) {
            schoolLevelOptions.push(this.state.schoolLevel.map((d, index) =>
                <Option value={d.schoolLevel} key={index}>{d.schoolLevel}</Option>
            ))
        }
        let countyOptions = [];
        let name = sessionStorage.getItem("departmentName")
        let id = parseInt(sessionStorage.getItem("departmentId"))
        countyOptions.push(<Option value={-id} key={-id}>{name.substring(0, name.indexOf("市"))}全市</Option>)
        if(this.state.countyList.length != 0){
            countyOptions.push(this.state.countyList.map((item) =>
                <Option value={item.id} key={item.id}>{item.name}</Option>
            ))
        }
        const { getFieldDecorator, getFieldValue } = this.props.form;
        let { sortedInfo, filteredInfo } = this.state;
        sortedInfo = sortedInfo || {};
        filteredInfo = filteredInfo || {};
        const columnsSearch = [{
            title: "序号",
            dataIndex: "key",
            key: "key"
        }, {
            title: "学校",
            dataIndex: "schoolname",
            key: "schoolname",
            filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                <div className="custom-filter-dropdown">
                    <Input
                        ref={ele => this.searchInput = ele}
                        value={selectedKeys[0]}
                        onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                        onPressEnter={this.handleSearch(selectedKeys, confirm)}
                    />
                    <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                    <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                </div>
            ),
            filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
            onFilter: (value, record) => record.schoolname.toLowerCase().includes(value.toLowerCase()),
            onFilterDropdownVisibleChange: (visible) => {
                if (visible) {
                    setTimeout(() => {
                        this.searchInput.focus();
                    });
                }
            }
        }, 
        sessionStorage.getItem("departmentType") == "教育局" ? 
        {
            title: "区县",
            dataIndex: "departmentName",
            key: "departmentName"
        }:{}, {
            title: "隐患发现个数",
            dataIndex: "dangernum",
            key: "dangernum",
            sorter: (a, b) => a.dangernum - b.dangernum,
            sortDirections: ['descend', 'ascend'],

        }, {
            title: "隐患处理个数",
            dataIndex: "dangerdealnum",
            key: "dangerdealnum",
            sorter: (a, b) => a.dangerdealnum - b.dangerdealnum,
            sortDirections: ['descend', 'ascend'],

        }, {
            title: '详情',
            dataIndex: 'action',
            key: 'action',
            render: (text, record) => {
                //  console.log("============================", record)
                return (
                    // <span>
                    //     <a
                    //         onClick={toSchoolUrl.bind(this, record)}
                    //         // href={this.stahoolUrl}   
                    //         target="_blank"
                    //     >
                    //         查看详情
                        // </a>
                        /* <Button onClick={this.toSchoolUrl.bind(this, record)}> 查看详情</Button> */
                    // </span>
                    <span>
                            <a
                                href="javascript:;"
                                onClick={
                                    this.showDetailDrawer.bind(this, record.schoolId)
                                }
                                > 
                                查看详情
                            </a>
                    </span>
                )
            }
        }]
        let labelCol = {
            sm: { span: 6 },
            xl: { span: 6 },
            xxl: { span: 5 },
        };

        let wrapperCol = {
            sm: { span: 18 },
            xl: { span: 18 },
            xxl: { span: 19 },
        };

        // Excel头部标题
        const header = [
            {
                title: '序号',
                dataIndex: 'key',
                key: 'key',
            }, {
                title: '学校',
                dataIndex: 'schoolname',
                key: 'schoolname',
            }, {
                title: '区县',
                dataIndex: 'departmentName',
                key: 'departmentName',
            }, {
                title: '隐患发现个数(次)',
                dataIndex: 'dangernum',
                key: 'dangernum',
            }, {
                title: '隐患处理个数(次)',
                dataIndex: 'dangerdealnum',
                key: 'dangerdealnum',
            }
        ]


        return (
            <div style={{ marginBottom: 16 }}>
                <Form style={{
                    padding: '12px',
                    backgroundColor: '#fafafa',
                    borderRadius: 8,
                    marginBottom: 16,
                }}
                    layout="inline"
                    onSubmit={this.searchSubmit}>
                    <Row>
                        <Col span={8}>
                            <FormItem
                                label="截止日期"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("deadline", {
                                    rules: [{
                                        type: 'array',
                                        required: false,
                                    }],
                                    initialValue: [ // 核心代码
                                        moment(this.getBeforeWeekTime(), dateFormat),
                                        moment(this.getBeforeDayTime(), dateFormat),
                                      ],
                                })(
                                    <RangePicker
                                        style={{ width: '100%' }}
                                        format="YYYY-MM-DD"
                                        onChange={this.handleSelectTime} />
                                )}
                            </FormItem>
                        </Col>
                        {sessionStorage.getItem("departmentType") == "教育局" ? (
                            <Col span={5}>
                            <FormItem
                                label="区县"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("county", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请选择区县"
                                        onSelect = {(e) => {
                                            if(e < 0){
                                                this.getSchoolLevelByEduId(parseInt(sessionStorage.getItem("departmentId")), 1)
                                            }else {
                                                this.getSchoolLevelByEduId(e, 0)
                                            }
                                        }}>
                                        {countyOptions}
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        )
                        :null
                        }
                        <Col span={8}>
                            <FormItem
                                label="学校类型"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("schoolLevel", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请选择学校类型">
                                        {schoolLevelOptions}
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8}>
                        <FormItem
                                label="数值"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("average", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请选择数值情况">
                                        <Option value={0} key={0}>所有</Option>
                                        <Option value={1} key={1}>低于平均值</Option>
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        <Col>
                            <FormItem
                                style={{ float: 'right' }}>
                                <Button type="primary" htmlType="submit">搜索</Button>
                                <Button style={{ marginLeft: 8 }} onClick={this.searchReset}>清空</Button>
                                <Button type="primary" style={{ marginLeft: 8 }} onClick={() =>  {
                                    exportExcel(header, this.state.columnData, "学校隐患个数排名.xlsx")
                                    }}>导出Excel
                                </Button>
                            </FormItem>
                        </Col>
                    </Row>
                </Form>
                <div>
                    {
                        this.state.isSearch ?
                            (
                                <div style={{
                                    marginBottom: 16,
                                    padding: 16,
                                    width: '100%',
                                    height: 350,
                                    border: '1px solid',
                                    borderColor: '#f5f5f5'
                                }}>
                                    <Skeleton loading={this.state.searchChartLoading} active>
                                        <ChartSearchDangerNum
                                            that={this}
                                            schoolName={this.state.schoolName}
                                            schoolResult={this.state.schoolResult}
                                            schoolResult2={this.state.schoolResult2}
                                            serialList={this.state.serialList}
                                            chartAvg={this.state.chartAvg}
                                            alldangernum={this.state.alldangernum}
                                            alldangerdealnum={this.state.alldangerdealnum}
                                            divId={'chartSearch'} />
                                    </Skeleton>
                                </div>
                            ) : null
                    }
                    <Table
                        dataSource={this.state.columnData}
                        columns={columnsSearch}
                        loading={this.state.tableLoading}
                        locale={{ emptyText: '暂无数据' }}
                        onChange={this.handleChange2}
                        rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                        pagination={{  //分页
                            total: this.state.searchData.length, //数据总数量
                            defaultPageSize: 10, //默认显示几条一页
                            //pageSize: 10,
                            showTotal: function (total) {  //设置显示一共几条数据
                                return '共 ' + total + ' 条数据';
                            },
                            showSizeChanger: true,
                            showQuickJumper: true,
                            pageSizeOptions: [5, 10, 20, 30]
                        }} />
                        {
                    this.state.detailExist ? (
                        <DangerConditionDetail
                            visible={this.state.detailVisible}
                            currentSchoolId={this.state.currentSchoolId}
                            startTime={this.state.startTime}
                            endTime={this.state.endTime}
                            that={this}
                            flag={this.state.flag} />
                    ) : null
                }
                </div>
            </div>
        );
    }
}
const EduDangerNumRank = Form.create()(eduDangerNumRank);

//校隐患次数排名柱状图
class ChartSearchDangerNum extends Component {
    constructor(props) {
        super(props);
        this.state = {
            schoolResult: props.schoolResult || [],
            //schoolResult: [[1281.0, 600.0, 72.0, 87, 94], [63.0, 0.0, -1.5, 98, 391]],
            schoolResult2: props.schoolResult2 || [],
            schoolName: props.schoolName || [],
            //schoolName: [[" 丰惠镇中心幼儿园", "第二实验幼儿园盛丰园区", "第一实验幼儿园和润花园区", "第一实验幼儿园新上海园区", "梯度中学"], ["第一实验幼儿园新上海园区", "梯度中学", "上浦镇中心幼儿园", "第一实验幼儿园新上海园区", "梯度中学"]],
            serialList: props.serialList || [],
            //serialList: ["1", "2"],
            that: props.that,
            currentIndex: 0,
            divId: props.divId,
            data1: 0,
            schoolNamePart: [],
            chartAvg: props.chartAvg,
            alldangernum: props.alldangernum || 0,
            alldangerdealnum: props.alldangerdealnum || 0,
        };

    }

    componentWillReceiveProps(props) {

        if (JSON.stringify(props.schoolName) != JSON.stringify(this.state.schoolName) && props.serialList.length > 0) {
            this.setState({
                that: props.that,
                schoolResult: props.schoolResult,
                schoolResult2: props.schoolResult2,
                schoolName: props.schoolName,
                serialList: props.serialList,
                chartAvg: props.chartAvg,
                alldangernum: props.alldangernum,
                alldangerdealnum: props.alldangerdealnum,
            }, () => {
                this.drawChart()
            })
        }
    }

    componentDidMount() {
        let optionData = [];
        if (this.state.schoolName.length != 0) {
            this.drawChart();
        }
    }




    drawChart() {

        let optionData = [];

        let chart = echarts.init(document.getElementById('chartSearch'));
        let option = {

            baseOption: {
                timeline: {
                    axisType: 'category',
                    triggerEvent: true,
                    playInterval: 1000,
                    data: this.state.serialList
                },
                title: {
                    text: '学校发现隐患个数排名',
                    left: 'center',
                    top: '10px',
                    subtext:'处理总个数/发现总个数：'+ this.state.alldangerdealnum + '个/' + this.state.alldangernum + '个',
                    subtextStyle: {
                        fontSize: 16
                    }
                },

                legend: {
                    // x: '100px',
                    left:'5%',
                    // y: '2px',
                    // bottom: 'bottom',
                    data: ['隐患发现个数', '隐患处理个数']
                },

                color: ['#3398DB'],
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                        type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                    }
                },
                toolbox: {
                    show: true,
                    feature: {
                        dataZoom: {
                            yAxisIndex: 'none'
                        },
                        dataView: { readOnly: false },
                        magicType: { type: ['line', 'bar'] },
                        restore: {},
                        saveAsImage: {}
                    }
                },
                grid: {
                    left: '5%',
                    right: '5%',
                    bottom: '50px',
                    top: '90px',
                    containLabel: true
                },
                xAxis: [
                    {
                        type: 'category',
                        data: this.state.schoolNamePart,
                        axisTick: {
                            alignWithLabel: true
                        },
                        axisLabel: {
                            textStyle: {
                                fontSize: 16
                            }
                        }
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        axisLabel: {
                            formatter: '{value}次',
                            textStyle: {
                                fontSize: 16
                            }
                        }
                    }
                ],

                series: [
                    { name: '隐患发现个数', type: 'bar' },
                    { name: '隐患处理个数', type: 'bar' },
                ],

            },
            options: []
        };

        for (var i = 0; i < this.state.schoolResult.length; i++) {
            let schoolNameList = [];
            for(var j = 0;j < this.state.schoolName[i].length; j++){
                let arr = this.state.schoolName[i][j].split("\n");
                schoolNameList.push(arr[0]);
            }
            
            option.options.push({
                xAxis: {
                    data: sessionStorage.getItem("departmentType") == "教育局" ? this.state.schoolName[i]
                    : schoolNameList
                },
                series: [                
                    {
                        name: '隐患处理个数',
                        type: 'bar',
                        data: this.state.schoolResult2[i],
                        barGap: '100%',
                        barMaxWidth: 25,
                        animation: false,
                        itemStyle:
                        {
                            color: 'rgb(255, 70, 131)',
                            normal: {
                                label: {
                                    show: true, //开启显示
                                    position: 'top', //在上方显示
                                    textStyle: { //数值样式
                                        color: 'black',
                                        fontSize: 14
                                    }
                                }
                            }
                        },
                        showBackground: true,
                        backgroundStyle: {
                            color: 'rgba(180, 180, 180, 0.2)'
                        },
                    },
                    {
                        name: '隐患发现个数',
                        type: 'bar',
                        data: this.state.schoolResult[i],
                        barGap: '100%',
                        barMaxWidth: 25,
                        animation: false,
                        itemStyle:
                            {
                                // color: 'rgb(255, 70, 131)',
                                //color: '#FFD700',
                                normal: {
                                   color: '#FFD700',
                                    label: {
                                        show: true, //开启显示
                                        position: 'top', //在上方显示
                                        textStyle: { //数值样式
                                            color: 'black',
                                            fontSize: 14
                                        }
                                    }
                                }
                            },
                        showBackground: true,
                        backgroundStyle: {
                            color: 'rgba(180, 180, 180, 0.2)'
                        },
                        // markLine: {
                        //     label: { formatter: '平均值: ' + this.state.chartAvg },
                        //     symbol: 'none',
                        //     data: [{
                        //         type: 'average',
                        //         name: '平均值',
                        //     }]
                        // },
            
                        markPoint: {
                            data: [
                                {
                                    type: 'max', name: '最大值'
                                }, {
                                    type: 'min', name: '最小值'
                                }
                            ]
                        }
                    }
                ]
            })
        }

      
        chart.setOption(option);
    

    }



    render() {
        let chartStyle = {
            height: '100%',
            width: '100%',
        };
        return (<div id={this.state.divId} style={chartStyle} />)
    }
}

class eduDangerCategory extends Component {
    constructor(props) {
        super(props);
        this.state = {
            alertVisible: false, //提示
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            tableLoading: true,
            filteredInfo: null,
            sortedInfo: null,
            searchData: [],
            schoolLevel: [],
            countyList: [],
            searchChartLoading: true,
            chartSearchData: {},
            chartSearchAvg: "",
            startTime: "",
            endTime: "",
            isSearch: false,
            departmentId: sessionStorage.getItem("departmentId"),
            schoolLevel1: undefined,
            departmentId1: undefined,
            startTime1: undefined,
            endTime1: undefined,
        };
    }
    componentWillMount() {
    }
    componentDidMount() {
        this.refreshData();
    }
    getBeforeDayTime() {
        var time = (new Date()).getTime() - 24 * 60 * 60 * 1000;
        var beforeday = new Date(time); // 获取的是前一天日期

        beforeday = beforeday.getFullYear() + "-" + (beforeday.getMonth() + 1 > 9
            ? (beforeday.getMonth() + 1) : "0" + (beforeday.getMonth()+1)) + "-" + (beforeday.getDate() > 9
                ? (beforeday.getDate()) : "0" + (beforeday.getDate())); //字符串拼接转格式：例如2018-08-19
        
        return beforeday
    }
    getBeforeWeekTime() {
        var time = (new Date()).getTime() - 24 * 60 * 60 * 1000 * 7;
        var beforeweek = new Date(time); // 获取的是前一周日期

        beforeweek = beforeweek.getFullYear() + "-" + (beforeweek.getMonth() + 1 > 9
            ? (beforeweek.getMonth() + 1) : "0" + (beforeweek.getMonth() + 1)) + "-" + (beforeweek.getDate() > 9
                ? (beforeweek.getDate()) : "0" + (beforeweek.getDate())); //字符串拼接转格式：例如2018-08-19
        return beforeweek
    }

    refreshData() {
        this.getCategoryInfo();

        let departmentId = -sessionStorage.getItem("departmentId")

        
        this.getSchoolLevelByEduId(sessionStorage.getItem("departmentId"), 1)
    

        getDepartmentApi(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                this.setState({
                    countyList: res.data
                });
            }).catch((e) => {
                console.log(e);
            })
    }

    getCategoryInfo = () => {
        this.props.form.validateFields((err, values) => {
            var schoolLevel;
            var departmentId;
            var startTime;
            var endTime;
            if (values.deadline == undefined && values.schoolLevel == undefined) {
                message.error('请至少填写一项条件再进行搜索');
            } else {
                if (values.schoolLevel != undefined) {
                    schoolLevel = values.schoolLevel
                }
                if(values.deadline != undefined){
                    startTime = moment(values.deadline[0]).format('YYYY-MM-DD');
                    endTime = moment(values.deadline[1]).format('YYYY-MM-DD');
                }
                if(!isNaN(values.county)){
                    departmentId = values.county
                }else{
                    departmentId = -parseInt(sessionStorage.getItem("departmentId"))
                }
                this.setState({
                    tableLoading: true,
                    schoolLevel1: schoolLevel,
                    departmentId1: departmentId,
                    startTime1: startTime,
                    endTime1: endTime,
                });
                let columnData = [];
                getEduDangerCategoryApi(departmentId, schoolLevel, startTime, endTime)
                    .then((res) => {
                        if (res.data.length == 0) {
                            this.setState({
                                columnData: [],
                                chartSearchData: [],
                                tableLoading: false,
                                isSearch: false
                            });
                        } else {
                            let chartSearchData = []
                            res.data.forEach((item, index) => {
                                columnData.push({
                                    key: index + 1,
                                    categoryId: item.categoryId,
                                    category: item.category,
                                    num: item.num,
                                });
                                chartSearchData.push({
                                    name: item.category,
                                    value: item.num
                                })
                            });
                            this.setState({
                                columnData: columnData,
                                searchChartLoading: false,
                                chartSearchData: chartSearchData,
                                tableLoading: false,
                                alertVisible: false,
                                isSearch: true
                            });
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });

            }
        });
    }

    searchSubmit = (e) => {
        
        e.preventDefault();
        this.getCategoryInfo();
        
    }
    clearAll = () => {
        this.setState({
            filteredInfo: null,
            sortedInfo: null,
        });
    }
    handleChange = (pagination, filters, sorter) => {
        this.setState({
            filteredInfo: filters,
            sortedInfo: sorter,
        });
    }
    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
    }
    handleSearchReset = clearFilters => () => {
        clearFilters();
    }
    onRef = (ref) => {
        this.child = ref
    }

    searchReset = () => {
        this.props.form.resetFields();
        // this.setState({
        //     isSearch: false,
        // })
    }

    setFullScreen(opts) {
        this.setState({
            fullScreenVisible: true,
        })
        let fullchart = echarts.init(document.getElementById('fullScreen'))
        fullchart.setOption(opts);
    }

    fullScreenCancel() {
        this.setState({
            fullScreenVisible: false,
        })
    }
    handleSelectTime = (value, dateString) => {
        if (dateString[0] != '' && dateString[1] != '') {
            this.setState({
                startTime: dateString[0],
                endTime: dateString[1],
            })
        }

    }

    getSchoolLevelByEduId(id, allType){
        getSchoolLevelByEduIdApi(id, allType)
            .then((res) => {
                this.setState({
                    schoolLevel: res.data,
                });

            })
    }

    showDetailDrawer(categoryId, schoolLevel, departmentId, startTime, endTime){
        // console.log('========', categoryId, schoolLevel, departmentId, startTime, endTime)
        this.setState({
            detailExist: true,
            detailVisible: true,
            currentCategoryId: categoryId,
            currentSchoolLevel: schoolLevel,
            currentDepartmentId: departmentId,
            currentStartTime: startTime,
            currentEndTime: endTime,
        })
    }
    handleDetailDrawerCancel() {
        this.setState({
            detailVisible: false,
        })
    }
    handleDetailDrawerClick(){
        this.setState({
        })
    }

    render() {
        let schoolLevelOptions = [];
        schoolLevelOptions.push(<Option value={null} key={-1}>全部</Option>)
        if (this.state.schoolLevel.length != 0) {
            schoolLevelOptions.push(this.state.schoolLevel.map((d, index) =>
                <Option value={d.schoolLevel} key={index}>{d.schoolLevel}</Option>
            ))
        }
        let countyOptions = [];
        let name = sessionStorage.getItem("departmentName")
        let id = parseInt(sessionStorage.getItem("departmentId"))
        countyOptions.push(<Option value={-id} key={-id}>{name.substring(0, name.indexOf("市"))}全市</Option>)
        if(this.state.countyList.length != 0){
            countyOptions.push(this.state.countyList.map((item) =>
                <Option value={item.id} key={item.id}>{item.name}</Option>
            ))
        }
        const { getFieldDecorator, getFieldValue } = this.props.form;
        let { sortedInfo, filteredInfo } = this.state;
        sortedInfo = sortedInfo || {};
        filteredInfo = filteredInfo || {};
        const columnsSearch = [{
            title: "序号",
            dataIndex: "key",
            key: "key"
        }, {
            title: "隐患类别",
            dataIndex: "category",
            key: "category",
            filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                <div className="custom-filter-dropdown">
                    <Input
                        ref={ele => this.searchInput = ele}
                        value={selectedKeys[0]}
                        onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                        onPressEnter={this.handleSearch(selectedKeys, confirm)}
                    />
                    <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                    <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                </div>
            ),
            filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
            onFilter: (value, record) => record.category.toLowerCase().includes(value.toLowerCase()),
            onFilterDropdownVisibleChange: (visible) => {
                if (visible) {
                    setTimeout(() => {
                        this.searchInput.focus();
                    });
                }
            }
        }, {
            title: "隐患个数",
            dataIndex: "num",
            key: "num",
            sorter: (a, b) => a.num - b.num,
            sortDirections: ['descend', 'ascend'],
        }, {
            title: '详情',
            dataIndex: 'action',
            key: 'action',
            render: (text, record) => {
                //  console.log("============================", record)
                return (
                    <span>
                            <a
                                href="javascript:;"
                                onClick={this.showDetailDrawer.bind(this, record.categoryId, this.state.schoolLevel1, this.state.departmentId1, this.state.startTime1, this.state.endTime1)}
                                > 
                                查看详情
                            </a>
                    </span>
                )
            }
        }]
        let labelCol = {
            sm: { span: 6 },
            xl: { span: 6 },
            xxl: { span: 5 },
        };

        let wrapperCol = {
            sm: { span: 18 },
            xl: { span: 18 },
            xxl: { span: 19 },
        };

        // Excel头部标题
        const header = [
            {
                title: '序号',
                dataIndex: 'key',
                key: 'key',
            }, {
                title: '隐患类别',
                dataIndex: 'category',
                key: 'category',
            }, {
                title: '隐患个数',
                dataIndex: 'num',
                key: 'num',
            }
        ]


        return (
            <div style={{ marginBottom: 16 }}>
                <Form style={{
                    padding: '12px',
                    backgroundColor: '#fafafa',
                    borderRadius: 8,
                    marginBottom: 16,
                }}
                    layout="inline"
                    onSubmit={this.searchSubmit}>
                    <Row>
                        <Col span={8}>
                            <FormItem
                                label="截止日期"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("deadline", {
                                    rules: [{
                                        type: 'array',
                                        required: false,
                                    }],
                                    initialValue: [ // 核心代码
                                        moment(this.getBeforeWeekTime(), dateFormat),
                                        moment(this.getBeforeDayTime(), dateFormat),
                                      ],
                                })(
                                    <RangePicker
                                        style={{ width: '100%' }}
                                        format="YYYY-MM-DD"
                                        onChange={this.handleSelectTime} />
                                )}
                            </FormItem>
                        </Col>
                        {sessionStorage.getItem("departmentType") == "教育局" ? (
                            <Col span={5}>
                            <FormItem
                                label="区县"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("county", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请选择区县"
                                        onSelect = {(e) => {
                                            if(e < 0){
                                                this.getSchoolLevelByEduId(parseInt(sessionStorage.getItem("departmentId")), 1)
                                            }else {
                                                this.getSchoolLevelByEduId(e, 0)
                                            }
                                        }}>
                                        {countyOptions}
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        )
                        :null
                        }
                        <Col span={8}>
                            <FormItem
                                label="学校类型"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("schoolLevel", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请选择学校类型">
                                        {schoolLevelOptions}
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        <Col>
                            <FormItem
                                style={{ float: 'right' }}>
                                <Button type="primary" htmlType="submit">搜索</Button>
                                <Button style={{ marginLeft: 8 }} onClick={this.searchReset}>清空</Button>
                                <Button type="primary" style={{ marginLeft: 8 }} onClick={() =>  {
                                    exportExcel(header, this.state.columnData, "学校隐患类型分布.xlsx")
                                    }}>导出Excel
                                </Button> 
                            </FormItem>
                        </Col>
                    </Row>
                </Form>
                <div>
                    {
                        this.state.isSearch ?
                            (
                                <div style={{
                                    marginBottom: 16,
                                    padding: 16,
                                    width: '100%',
                                    height: 350,
                                    border: '1px solid',
                                    borderColor: '#f5f5f5'
                                }}>
                                    <Skeleton loading={this.state.searchChartLoading} active>
                                        <ChartSearchDangerCategory
                                            that={this}
                                            chartData={this.state.chartSearchData}
                                        />
                                    </Skeleton>
                                </div>
                            ) : null
                    }
                    <Table
                        dataSource={this.state.columnData}
                        columns={columnsSearch}
                        loading={this.state.tableLoading}
                        locale={{ emptyText: '暂无数据' }}
                        onChange={this.handleChange2}
                        rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                        pagination={{  //分页
                            total: this.state.searchData.length, //数据总数量
                            defaultPageSize: 10, //默认显示几条一页
                            //pageSize: 10,
                            showTotal: function (total) {  //设置显示一共几条数据
                                return '共 ' + total + ' 条数据';
                            },
                            showSizeChanger: true,
                            showQuickJumper: true,
                            pageSizeOptions: [5, 10, 20, 30]
                        }} />
                        {
                            this.state.detailExist ? (
                                <DangerCategoryDetail
                                    visible={this.state.detailVisible}
                                    currentCategoryId={this.state.currentCategoryId}
                                    currentSchoolLevel={this.state.currentSchoolLevel}
                                    currentDepartmentId={this.state.currentDepartmentId}
                                    currentStartTime={this.state.currentStartTime}
                                    currentEndTime={this.state.currentEndTime}
                                    that={this} />
                            ) : null
                        }
                </div>
            </div>
        );
    }

}
const EduDangerCategory = Form.create()(eduDangerCategory)

//安全隐患分类查看详情划窗
class dangerCategoryDetail extends Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: props.visible,
            that: props.that,
            currentCategoryId: props.currentCategoryId,
            currentSchoolLevel: props.currentSchoolLevel,
            currentDepartmentId: props.currentDepartmentId,
            currentStartTime: props.currentStartTime,
            currentEndTime: props.currentEndTime,
            updateVisible: false,
            detailVisible: false,
            alertVisible: false, //提示
            confirmLoading: false,
            previewVisible: false,
            previewImage: '',
            msg: "", //提交失败时的提示语
            tableLoading: true,
            data: [],
            filteredInfo: null,
            sortedInfo: null,
            // searchTextAddress: '',
            // searchTextReporter: '',
           
            allCategory: [],
            allStatus: [],
            isSearch: false,
            realNameArr: [], //上报人的autocomplete数据
            existCategory: [],
            searchData: [],
            test:true,
            searchChartLoading: true,
            chartSafetySceneSearchData: {}
        };
        //console.log('currentInspectPlanIds', props.currentInspectPlanIds)
    }

    componentDidMount() {
        this.refreshData(this.props.currentCategoryId, this.props.currentSchoolLevel, this.props.currentDepartmentId, this.props.currentStartTime, this.props.currentEndTime);
    }

    componentWillReceiveProps(props) {
        this.setState({
            currentCategoryId: props.currentCategoryId,
            currentSchoolLevel: props.currentSchoolLevel,
            currentDepartmentId: props.currentDepartmentId,
            currentStartTime: props.currentStartTime,
            currentEndTime: props.currentEndTime,
            visible: props.visible,
            that: props.that,
        });
        if (props.visible) {
            this.refreshData(props.currentCategoryId, props.currentSchoolLevel, props.currentDepartmentId, props.currentStartTime, props.currentEndTime);
        }
    }
  
 

    refreshData(currentCategoryId, currentSchoolLevel, currentDepartmentId, currentStartTime, currentEndTime) {
        this.setState({
            confirmLoading: true,
            tableLoading: true
        })
        
        let columnData = [];
        let statusData = [];

        getSafetySceneByCategory(currentDepartmentId, currentSchoolLevel, currentCategoryId, currentStartTime, currentEndTime)
                    .then((res) => {
                        res.data.forEach((item, index) => {
                            columnData.push({
                                key: index + 1,
                                id: item.id,
                                safetyLevel: item.safetyLevel,
                                name: item.name,
                                address: item.address,
                                reporterId: item.reporter,
                                reporterName: item.reportName,
                                status: item.statusString,
                                createTime: item.createTime,
                                modifyTime: item.modifyTime,
                                categoryId: item.categoryId,
                                categoryName: item.categoryName,
                                dealName: item.dealName
                            });
                            statusData.push(item.statusString);
                        });

                        this.setState({
                            columnData: columnData,
                            tableLoading: false,
                            preData: columnData
                        });
                        let statusDataUnique = statusData.filter(function (element, index, array) {
                            return array.indexOf(element) === index;
                        });
                        let allStatus = statusDataUnique.map((d, index) => {
                            return ({
                                text: d,
                                value: d,
                            })
                        })
                        this.setState({
                            allStatus: allStatus,
                        });
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });
    }


    formatTime(date) {
        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const day = date.getDate();
        const hour = date.getHours();
        const minute = date.getMinutes();
        const second = date.getSeconds();
        return [year, month, day].map(this.formatNumber).join('-') + ' ' + [hour, minute, second].map(this.formatNumber).join(':');
    }

    formatNumber(n) {
        n = n.toString();
        return n[1] ? n : '0' + n;
    }


    showDetailModal(id, safetyLevel, address, reporterName, status,
        createTime, modifyTime, categoryName) {
        let level = "";
        switch (safetyLevel) {
            case 1: level = "安全"; break;
            case 2: level = "一般"; break;
            case 3: level = "危险"; break;
            case 4: level = "非常危险"; break;
            case 5: level = "巡检排查"; break;
        }
        this.setState({
            detailVisible: true,
            currentId: id,
            currentSafetyLevel: level,
            currentAddress: address,
            currentReporterName: reporterName,
            currentStatus: status,
            currentCreateTime: createTime,
            currentModifyTime: modifyTime,
            currentCategoryName: categoryName,
        })
    }

    //关闭 alert 的提示
    handleClose() {
        this.setState({ alertVisible: false });
    }
    //关闭模态框
    handleUpdateCancel() {
        let val = this.refs.updateSafetysceneFormValue;
        val.resetFields();
        this.setState({
            alertVisible: false,
            updateVisible: false,
        });
    }
    //关闭模态框
    handleDetailCancel() {
        this.setState({
            alertVisible: false,
            detailVisible: false,
        });
    }

    clearAll = () => {
        this.setState({
            filteredInfo: null,
            sortedInfo: null,
        });

    }

    handleChange = (pagination, filters, sorter) => {
        //console.log('Various parameters', pagination, filters, sorter);
        this.setState({
            filteredInfo: filters,
            sortedInfo: sorter,
        });
    }

    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
        // this.setState({
        //     searchTextAddress: selectedKeys[0],
        //     searchTextReporter: selectedKeys[0]
        // });
    }

    handleSearchReset = clearFilters => () => {
        clearFilters();
        // this.setState({
        //     searchTextAddress: '',
        //     searchTextReporter: '',
        // });
    }

    getBeforeDayTime() {
        var time = (new Date()).getTime() - 24 * 60 * 60 * 1000;
        var beforeday = new Date(time); // 获取的是前一天日期

        beforeday = beforeday.getFullYear() + "-" + (beforeday.getMonth() + 1 > 9
            ? (beforeday.getMonth() + 1) : "0" + (beforeday.getMonth()+1)) + "-" + (beforeday.getDate() > 9
                ? (beforeday.getDate()) : "0" + (beforeday.getDate())); //字符串拼接转格式：例如2018-08-19
        
        return beforeday
    }
    getBeforeWeekTime() {
        var time = (new Date()).getTime() - 24 * 60 * 60 * 1000 * 7;
        var beforeweek = new Date(time); // 获取的是前一周日期

        beforeweek = beforeweek.getFullYear() + "-" + (beforeweek.getMonth() + 1 > 9
            ? (beforeweek.getMonth() + 1) : "0" + (beforeweek.getMonth() + 1)) + "-" + (beforeweek.getDate() > 9
                ? (beforeweek.getDate()) : "0" + (beforeweek.getDate())); //字符串拼接转格式：例如2018-08-19
        return beforeweek
    }

    searchReset = () => {
        this.props.form.resetFields();
        this.setState({
            isSearch: false,
            columnData: this.state.preData,
        })
    }

    setFullScreen(opts) {
        this.setState({
            fullScreenVisible: true,
        })
        let fullchart = echarts.init(document.getElementById('fullScreen'))
        fullchart.setOption(opts);
    }

    fullScreenCancel() {
        this.setState({
            fullScreenVisible: false,
        })
    }

    render() {
        
        let { sortedInfo, filteredInfo } = this.state;
        sortedInfo = sortedInfo || {};
        filteredInfo = filteredInfo || {};

        let keyWidth = undefined;
        let nameWidth = undefined;
        let reporterNameWidth = undefined;
        let statusWidth = undefined;
        let actionWidth = undefined;
        let timeWidth = undefined;

        let winWidth;
        // 获取窗口宽度
        if (window.innerWidth)
            winWidth = window.innerWidth;
        else if ((document.body) && (document.body.clientWidth))
            winWidth = document.body.clientWidth;
        if (winWidth < 1500) {
            keyWidth = 60;
            nameWidth = 110;
            reporterNameWidth = 90;
            statusWidth = 80;
            actionWidth = 110;
            timeWidth = 120;
        }

        const columns = [{
            title: "序号",
            dataIndex: "key",
            key: "key",
            width: keyWidth,
        }, {
            title: "学校名称",
            dataIndex: "name",
            key: "name",
            width: nameWidth,
            filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                <div className="custom-filter-dropdown">
                    <Input
                        ref={ele => this.searchInput = ele}
                        value={selectedKeys[0]}
                        onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                        onPressEnter={this.handleSearch(selectedKeys, confirm)}
                    />
                    <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                    <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                </div>
            ),
            filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
            onFilter: (value, record) => record.name.toLowerCase().includes(value.toLowerCase()),
            onFilterDropdownVisibleChange: (visible) => {
                if (visible) {
                    setTimeout(() => {
                        this.searchInput.focus();
                    });
                }
            }
        }, {
            title: "地址",
            dataIndex: "address",
            key: "address",
            filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                <div className="custom-filter-dropdown">
                    <Input
                        ref={ele => this.searchInput = ele}
                        value={selectedKeys[0]}
                        onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                        onPressEnter={this.handleSearch(selectedKeys, confirm)}
                    />
                    <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                    <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                </div>
            ),
            filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
            onFilter: (value, record) => record.address.toLowerCase().includes(value.toLowerCase()),
            onFilterDropdownVisibleChange: (visible) => {
                if (visible) {
                    setTimeout(() => {
                        this.searchInput.focus();
                    });
                }
            }
        }, {
            title: "安全等级",
            dataIndex: "safetyLevel",
            key: "safetyLevel",
            sorter: (a, b) => a.safetyLevel - b.safetyLevel,
            sortOrder: sortedInfo.columnKey === 'safetyLevel' && sortedInfo.order,
            render: (text) => (
                <div style={{ width: '90px' }}>
                    <img
                        style={{ width: '100%' }}
                        src={require('../img/safetyLevel' + text + '.png')} />
                </div>
            )
        }, {
            title: "上报人",
            dataIndex: "reporterName",
            key: "reporterName",
            width: reporterNameWidth,
            filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                <div className="custom-filter-dropdown">
                    <Input
                        ref={ele => this.searchInput = ele}
                        value={selectedKeys[0]}
                        onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                        onPressEnter={this.handleSearch(selectedKeys, confirm)}
                    />
                    <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                    <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                </div>
            ),
            filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
            onFilter: (value, record) => record.reporterName.toLowerCase().includes(value.toLowerCase()),
            onFilterDropdownVisibleChange: (visible) => {
                if (visible) {
                    setTimeout(() => {
                        this.searchInput.focus();
                    });
                }
            }
        }, {
            title: "状态",
            dataIndex: "status",
            key: "status",
            width: statusWidth,
            filters: this.state.allStatus,
            filteredValue: filteredInfo.status || null,
            onFilter: (value, record) => record.status.includes(value),
            filterIcon: filtered => <Icon type="filter" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
            render: (text) => {
                if (text == '已处理') { return (<span style={{ color: 'green' }}>已处理</span>) }
                else if (text == '未处理') { return (<span style={{ color: 'red' }}>未处理</span>) }
                else if (text == '处理中') { return (<span style={{ color: '#096dd9' }}>处理中</span>) }
            },
        }, {
            title: "上报时间",
            dataIndex: "createTime",
            key: "createTime",
            width: timeWidth,
            sorter: (a, b) => new Date(a.createTime).getTime() - new Date(b.createTime).getTime(),
            sortOrder: sortedInfo.columnKey === 'createTime' && sortedInfo.order,
        }, {
            title: "处理时间",
            dataIndex: "modifyTime",
            key: "modifyTime",
            width: timeWidth,
            sorter: (a, b) => new Date(a.modifyTime).getTime() - new Date(b.modifyTime).getTime(),
            sortOrder: sortedInfo.columnKey === 'modifyTime' && sortedInfo.order,
            render: (text, record) => {
                if (record.status == '已处理') { return (<span>{text}</span>) }
                else if (record.status == '未处理') { return (<span>-</span>) }
            },
        }, {
            title: "处理人",
            dataIndex: "dealName",
            key: "dealName",
            width: reporterNameWidth,
            filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                <div className="custom-filter-dropdown">
                    <Input
                        ref={ele => this.searchInput = ele}
                        value={selectedKeys[0]}
                        onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                        onPressEnter={this.handleSearch(selectedKeys, confirm)}
                    />
                    <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                    <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                </div>
            ),
            filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
            onFilter: (value, record) => record.reporterName.toLowerCase().includes(value.toLowerCase()),
            onFilterDropdownVisibleChange: (visible) => {
                if (visible) {
                    setTimeout(() => {
                        this.searchInput.focus();
                    });
                }
            },
            render: (text, record) => {
                if (record.status == '未处理') { return (<span>-</span>) }
                else {
                    return (<span>{text}</span>)
                }
            }
        }, {
            title: "操作详情",
            key: "action",
            width: actionWidth,
            render: (text, record) => {
                    return (
                        <span>
                            <a href="javascript:;" onClick={this.showDetailModal.bind(this,
                                record.id, record.safetyLevel, record.address,
                                record.reporterName, record.status, record.createTime,
                                record.modifyTime, record.categoryName)}>详细</a>
                        </span>
                    )
            }
        }];

        // Excel头部标题
        const header = [
            {
            title: "序号",
            dataIndex: "key",
            key: "key",
        }, {
            title: "学校名称",
            dataIndex: "name",
            key: "name",
        }, {
            title: "地址",
            dataIndex: "address",
            key: "address",
        }, {
            title: "安全等级",
            dataIndex: "safetyLevel",
            key: "safetyLevel",
        }, {
            title: "上报人",
            dataIndex: "reporterName",
            key: "reporterName",
        }, {
            title: "状态",
            dataIndex: "status",
            key: "status",
        }, {
            title: "上报时间",
            dataIndex: "createTime",
            key: "createTime",
        }, {
            title: "处理时间",
            dataIndex: "modifyTime",
            key: "modifyTime",
        }, {
            title: "处理人",
            dataIndex: "dealName",
            key: "dealName",
        }
        ]
        let excelData = []
        if(this.state.columnData != undefined) {
            let temp = JSON.parse(JSON.stringify(this.state.columnData))
            temp.map((d, index) => {
                if(d.status == '未处理') {
                    d.modifyTime = '-'
                    d.dealName = '-'
                }
                switch(d.safetyLevel) {
                    case 1: 
                        d.safetyLevel = "安全" 
                        break;
                    case 2:
                        d.safetyLevel = "一般" 
                        break;
                    case 3:
                        d.safetyLevel = "危险" 
                        break;
                    case 4:
                        d.safetyLevel = "非常危险" 
                        break;
                    case 5:
                        d.safetyLevel = "巡检排查" 
                        break;
                }
                excelData.push(d)
            })
        }
        return (
            <div>
                <Drawer
                    bodyStyle={{ paddingBottom: 80 }}
                    width={0.85*window.screen.width}
                    title='隐患类型分布详情'
                    visible={this.state.visible}
                    onClose={this.state.that.handleDetailDrawerCancel.bind(this.state.that)}
                    destroyOnClose={true}
                    closable
                >
                <Button type="primary" style={{ marginBottom: 24 }} onClick={() =>  {
                    exportExcel(header, excelData, "隐患类型分布详情.xlsx")
                }}>导出Excel
                </Button> 
                <div style={{ marginBottom: 16 }}>
                 
                <Drawer
                    bodyStyle={{ paddingBottom: 80 }}
                    width={600}
                    title={'安全现场详细信息'}
                    visible={this.state.detailVisible}
                    onClose={this.handleDetailCancel.bind(this)}
                    destroyOnClose={true}
                    closable
                >
                    <SafetysceneDetail
                        currentId={this.state.currentId} currentSafetyLevel={this.state.currentSafetyLevel}
                        currentAddress={this.state.currentAddress} currentReporterName={this.state.currentReporterName}
                        currentStatus={this.state.currentStatus} currentCreateTime={this.state.currentCreateTime}
                        currentModifyTime={this.state.currentModifyTime} currentCategoryName={this.state.currentCategoryName} />
                    {
                        this.state.alertVisible ?
                            (
                                <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                            ) : null
                    }
                    <div
                        style={{
                            position: 'absolute',
                            left: 0,
                            bottom: 0,
                            width: '100%',
                            borderTop: '1px solid #e9e9e9',
                            padding: '10px 16px',
                            background: '#fff',
                            textAlign: 'right',
                        }}
                    >
                        <Button key="submit" type="primary" size="large"
                            onClick={this.handleDetailCancel.bind(this)}>关闭</Button>
                    </div>
                </Drawer>

                <Table
                    dataSource={this.state.columnData}
                    columns={columns}
                    loading={this.state.tableLoading}
                    locale={{ emptyText: '暂无数据' }}
                    rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                    onChange={this.handleChange}
                    pagination={{  //分页
                        total: this.state.data.length, //数据总数量
                        defaultPageSize: 10, //默认显示几条一页
                        //pageSize: 10,
                        showTotal: function (total) {  //设置显示一共几条数据
                            return '共 ' + total + ' 条数据';
                        },
                        showSizeChanger: true,
                        showQuickJumper: true,
                        pageSizeOptions: [5, 10, 20, 30]
                    }} />
                </div>
                    
                    <div
                        style={{
                            position: 'absolute',
                            left: 0,
                            bottom: 0,
                            width: '100%',
                            borderTop: '1px solid #e9e9e9',
                            padding: '10px 16px',
                            background: '#fff',
                            textAlign: 'right',
                        }}
                    >
                        <Button size="large" onClick={this.state.that.handleDetailDrawerCancel.bind(this.state.that)}
                            style={{ marginRight: 20 }}>关闭</Button>
                    </div>
                </Drawer>
                
            </div>

        );
    }
}
const DangerCategoryDetail = Form.create()(dangerCategoryDetail);

//学校隐患分布饼状图
class ChartSearchDangerCategory extends Component {
    constructor(props) {
        super(props);
        this.state = {
            chartData: props.chartData,
            that: props.that
        };
    }

    componentWillReceiveProps(props) {
        if (JSON.stringify(props.chartData) != JSON.stringify(this.state.chartData)) {
            this.setState({
                chartData: props.chartData,
                that: props.that
            }, () => {
                this.drawChart();
            })
        }
    }

    componentDidMount() {
        this.drawChart();
    }

    drawChart() {
        
        if (JSON.stringify(this.state.chartData) != '[]') {
            // console.log(this.state.chartData);
            let alldangernum = 0
            this.state.chartData.forEach((item, index)=>{
                alldangernum += parseInt(item.value)
            })
            let chart = echarts.init(document.getElementById('chartSearch'));
            chart.setOption({
                title: {
                    text: '学校隐患分布(共'+alldangernum+'个）',
                    subtext: '',
                    x: 'center'
                },
                tooltip: {
                    trigger: 'item'
                },
                legend: {
                    orient: 'vertical',
                    left: '7.5%',  //图例距离左的距离
                    y: 'center',  //图例上下居中
                },
                series: [
                    {
                        name: '隐患类别分布',
                        type: 'pie',
                        radius: ['35%', '60%'],
                        center: ['50%', '55%'],
                        avoidLabelOverlap: false,
                        itemStyle: {
                            borderRadius: 10,
                            borderColor: '#fff',
                            borderWidth: 2,
                            normal: {
                                label: {
                                    show: true,
                                    formatter: '{b} : {c} ({d}%)',
                                    textStyle: {
                                        fontSize: 16
                                    },
                                },
                                labelLine: { show: true }
                            }
                        },
                        data: this.state.chartData
                    }
                ]
            })
            window.onresize = chart.resize;
        }

    }

    render() {
        let chartStyle = {
            height: '100%',
            width: '100%',
        };
        return (<div id='chartSearch' style={chartStyle} />)
    }
}

//学校隐患处理率
class eduDangerDealRateRank extends Component {
    constructor(props) {
        super(props);
        this.state = {
            alertVisible: false, //提示
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            tableLoading: true,
            filteredInfo: null,
            sortedInfo: null,
            searchData: [],
            schoolLevel: [],
            countyList: [],
            searchChartLoading: true,
            chartSearchData: {},
            chartSearchAvg: "",
            startTime: "",
            endTime: "",
            isSearch: false,
            departmentId: sessionStorage.getItem("departmentId"),
            detailVisible: false,
            detailExist: false,
            flag:false
        };
    }
    componentWillMount() {
    }
    componentDidMount() {
        this.refreshData();
    }
    getBeforeDayTime() {
        var time = (new Date()).getTime() - 24 * 60 * 60 * 1000;
        var beforeday = new Date(time); // 获取的是前一天日期

        beforeday = beforeday.getFullYear() + "-" + (beforeday.getMonth() + 1 > 9
            ? (beforeday.getMonth() + 1) : "0" + (beforeday.getMonth()+1)) + "-" + (beforeday.getDate() > 9
                ? (beforeday.getDate()) : "0" + (beforeday.getDate())); //字符串拼接转格式：例如2018-08-19
        
        return beforeday
    }
    getBeforeWeekTime() {
        var time = (new Date()).getTime() - 24 * 60 * 60 * 1000 * 7;
        var beforeweek = new Date(time); // 获取的是前一周日期

        beforeweek = beforeweek.getFullYear() + "-" + (beforeweek.getMonth() + 1 > 9
            ? (beforeweek.getMonth() + 1) : "0" + (beforeweek.getMonth() + 1)) + "-" + (beforeweek.getDate() > 9
                ? (beforeweek.getDate()) : "0" + (beforeweek.getDate())); //字符串拼接转格式：例如2018-08-19
        return beforeweek
    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        let columnData = [];
        let schoolLevel;
        var startTime = this.getBeforeWeekTime()
        var endTime = this.getBeforeDayTime()

        let departmentId = -sessionStorage.getItem("departmentId")

        getEduDangerDealRateApi(departmentId, schoolLevel, startTime, endTime)
            .then((res) => {
                res.data.edudangerdealraterankList.forEach((item, index) => {
                    columnData.push({
                        key: index + 1,
                        schoolname: item.schoolname,
                        dangernum: item.dangernum,
                        dangerdealnum: item.dangerdealnum,
                        dangerdealrate: item.dangerdealrate,
                        dangerdealpoints: item.dangerdealpoints,
                        departmentName: item.departmentName,
                        departmentId: item.departmentId
                    });
                });
                this.setState({
                    columnData: columnData,
                    startTime: startTime,
                    endTime: endTime,
                    tableLoading: false,
                    alertVisible: false,
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

            getEduDangerDealRateApi2(departmentId, schoolLevel, startTime, endTime)
            .then((res) => {
                if (res.data.serialList.length == 0) {
                    this.setState({
                        schoolResult: [],
                        schoolName: [],
                        serialList: [],
                        chartAvg: "",
                        tableLoading: false,
                        isSearch: false
                    });
                } else {
                    this.setState({
                        schoolResult: res.data.schoolResults,
                        schoolName: res.data.schoolNames,
                        serialList: res.data.serialList,
                        chartAvg: res.data.edudangerdealpointsavg,
                        searchChartLoading: false,
                        tableLoading: false,
                        alertVisible: false,
                        isSearch: true
                    });
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

        this.getSchoolLevelByEduId(sessionStorage.getItem("departmentId"), 1)
    

        getDepartmentApi(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                this.setState({
                    countyList: res.data
                });
            }).catch((e) => {
                console.log(e);
            })
    }

    searchSubmit = (e) => {
        var schoolLevel;
        var departmentId;
        e.preventDefault();
        this.props.form.validateFields((err, values) => {

            if (values.deadline == undefined && values.schoolLevel == undefined) {
                message.error('请至少填写一项条件再进行搜索');
            } else {
                if (values.schoolLevel != undefined) {
                    schoolLevel = values.schoolLevel
                }
                if(!isNaN(values.county)){
                    departmentId = values.county
                }else{
                    departmentId = -parseInt(sessionStorage.getItem("departmentId"))
                }
                this.setState({
                    tableLoading: true
                });
                let columnData = [];
                getEduDangerDealRateApi(departmentId, schoolLevel, this.state.startTime, this.state.endTime)
                    .then((res) => {
                        res.data.edudangerdealraterankList.forEach((item, index) => {
                            columnData.push({
                                key: index + 1,
                                schoolname: item.schoolname,
                                dangernum: item.dangernum,
                                dangerdealnum: item.dangerdealnum,
                                dangerdealrate: item.dangerdealrate,
                                dangerdealpoints: item.dangerdealpoints,
                                departmentName: item.departmentName,
                                departmentId : item.departmentId
                            });
                        });
                        this.setState({
                            columnData: columnData,
                            tableLoading: false,
                            alertVisible: false,
                        });
                        if(values.average == 1){
                            let columnDataAvg = [];
                            let columnDataTemp = this.state.columnData;
                            let sum = 0;
                            for(let i = 0;i < columnDataTemp.length; i++){
                                sum += parseFloat(columnDataTemp[i].dangerdealpoints);
                            }
                            let avg = sum / columnDataTemp.length;
                            let index = 1;
                            for(let i = 0;i < columnDataTemp.length;i ++){
                                if(parseFloat(columnDataTemp[i].dangerdealpoints) <= avg){
                                    columnDataTemp[i].key = index++;
                                    columnDataAvg.push(columnDataTemp[i]);
                                }
                            }
                            this.setState({
                                columnData: columnDataAvg
                            })
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });
                getEduDangerDealRateApi2(departmentId, schoolLevel, this.state.startTime, this.state.endTime)
                    .then((res) => {
                        if (res.data.serialList.length == 0) {
                            this.setState({
                                schoolResult: [],
                                schoolName: [],
                                serialList: [],
                                chartAvg: "",
                                tableLoading: false,
                                isSearch: false
                            });
                        } else {
                            this.setState({
                                schoolResult: res.data.schoolResults,
                                schoolName: res.data.schoolNames,
                                serialList: res.data.serialList,
                                chartAvg: res.data.edudangerdealpointsavg,
                                searchChartLoading: false,
                                tableLoading: false,
                                alertVisible: false,
                                isSearch: true
                            });
                            if(values.average == 1){
                                let schoolResultAvg = [];
                                let schoolNameAvg = [];
                                let serialListAvg = [];
                                let t1 = [];
                                let t3 = [];
                                let count = 0;
                                for(let i = 0;i < this.state.schoolResult.length;i++){
                                    for(let j = 0;j < this.state.schoolResult[i].length;j++){
                                        if(parseFloat(this.state.schoolResult[i][j]) <= parseFloat(this.state.chartAvg)){
                                            if(count != 0 && count % 5 == 0){
                                                schoolResultAvg.push(t1);
                                                schoolNameAvg.push(t3);
                                                serialListAvg.push(parseInt((count-1) / 5) + 1);
                                                t1 = [];
                                                t3 = [];
                                            }
                                            t1.push(this.state.schoolResult[i][j]);
                                            t3.push(this.state.schoolName[i][j]);
                                            count++;
                                        }
                                    }
                                }
                                if(t1.length != 0){
                                    schoolResultAvg.push(t1);
                                    schoolNameAvg.push(t3);
                                    serialListAvg.push(parseInt((count-1) / 5) + 1);
                                }
                                this.setState({
                                    schoolResult: schoolResultAvg,
                                    schoolName: schoolNameAvg,
                                    serialList: serialListAvg,
                                })
                            }
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });



            }
        });
    }
    clearAll = () => {
        this.setState({
            filteredInfo: null,
            sortedInfo: null,
        });
    }
    handleChange = (pagination, filters, sorter) => {
        this.setState({
            filteredInfo: filters,
            sortedInfo: sorter,
        });
    }
    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
    }
    handleSearchReset = clearFilters => () => {
        clearFilters();
    }
    onRef = (ref) => {
        this.child = ref
    }

    searchReset = () => {
        this.props.form.resetFields();
    }

    setFullScreen(opts) {
        this.setState({
            fullScreenVisible: true,
        })
        let fullchart = echarts.init(document.getElementById('fullScreen'))
        fullchart.setOption(opts);
    }

    fullScreenCancel() {
        this.setState({
            fullScreenVisible: false,
        })
    }
    handleSelectTime = (value, dateString) => {
        if (dateString[0] != '' && dateString[1] != '') {
            this.setState({
                startTime: dateString[0],
                endTime: dateString[1],
            })
        }

    }

    handleChange2() {
        console.log("handleChange2()=========================")
    }

    getSchoolLevelByEduId(id, allType){
        getSchoolLevelByEduIdApi(id, allType)
            .then((res) => {
                this.setState({
                    schoolLevel: res.data,
                });

            })
    }
    showDetailDrawer(departmentId){
        // console.log('========', record)
        this.setState({
            detailExist: true,
            detailVisible: true,
            currentSchoolId: departmentId,
            flag:true
        })
    }
    handleDetailDrawerCancel() {
        this.setState({
            detailVisible: false,
            flag:false,
        })
    }
    handleDetailDrawerClick(){
        this.setState({
            flag:false,
        })
    }

    render() {
        let schoolLevelOptions = [];
        schoolLevelOptions.push(<Option value={null} key={-1}>全部</Option>)
        if (this.state.schoolLevel.length != 0) {
            schoolLevelOptions.push(this.state.schoolLevel.map((d, index) =>
                <Option value={d.schoolLevel} key={index}>{d.schoolLevel}</Option>
            ))
        }
        let countyOptions = [];
        let name = sessionStorage.getItem("departmentName")
        let id = parseInt(sessionStorage.getItem("departmentId"))
        countyOptions.push(<Option value={-id} key={-id}>{name.substring(0, name.indexOf("市"))}全市</Option>)
        if(this.state.countyList.length != 0){
            countyOptions.push(this.state.countyList.map((item) =>
                <Option value={item.id} key={item.id}>{item.name}</Option>
            ))
        }
        const { getFieldDecorator, getFieldValue } = this.props.form;
        let { sortedInfo, filteredInfo } = this.state;
        sortedInfo = sortedInfo || {};
        filteredInfo = filteredInfo || {};
        const columnsSearch = [{
            title: "序号",
            dataIndex: "key",
            key: "key"
        }, {
            title: "学校",
            dataIndex: "schoolname",
            key: "schoolname",
            filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                <div className="custom-filter-dropdown">
                    <Input
                        ref={ele => this.searchInput = ele}
                        value={selectedKeys[0]}
                        onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                        onPressEnter={this.handleSearch(selectedKeys, confirm)}
                    />
                    <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                    <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                </div>
            ),
            filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
            onFilter: (value, record) => record.schoolname.toLowerCase().includes(value.toLowerCase()),
            onFilterDropdownVisibleChange: (visible) => {
                if (visible) {
                    setTimeout(() => {
                        this.searchInput.focus();
                    });
                }
            }
        }, 
        sessionStorage.getItem("departmentType") == "教育局" ? 
        {
            title: "区县",
            dataIndex: "departmentName",
            key: "departmentName"
        }:{}, {
            title: "隐患发现数",
            dataIndex: "dangernum",
            key: "dangernum",
            sorter: (a, b) => a.dangernum - b.dangernum,
            sortDirections: ['descend', 'ascend'],

        }, {
            title: "隐患处理数",
            dataIndex: "dangerdealnum",
            key: "dangerdealnum",
            sorter: (a, b) => a.dangerdealnum - b.dangerdealnum,
            sortDirections: ['descend', 'ascend'],

        }, {
            title: "隐患结案率(%)",
            dataIndex: "dangerdealrate",
            key: "dangerdealrate",
            sorter: (a, b) => a.dangerdealrate - b.dangerdealrate,
            sortDirections: ['descend', 'ascend'],

        }, {
            title: "隐患积分",
            dataIndex: "dangerdealpoints",
            key: "dangerdealpoints",
            sorter: (a, b) => a.dangerdealpoints - b.dangerdealpoints,
            sortDirections: ['descend', 'ascend'],
        },
        {
            title: '详情',
            dataIndex: 'action',
            key: 'action',
            render: (text, record) => {
                //  console.log("============================", record)
                return (
                    // <span>
                    //     <a
                    //         onClick={toSchoolUrl.bind(this, record)}
                    //         // href={this.stahoolUrl}   
                    //         target="_blank"
                    //     >
                    //         查看详情
                    //     </a>
                        /* <Button onClick={this.toSchoolUrl.bind(this, record)}> 查看详情</Button> */
                    // </span>
                    <span>
                            <a
                                href="javascript:;"
                                onClick={this.showDetailDrawer.bind(this, record.departmentId)}
                                > 
                                查看详情
                            </a>
                    </span>
                )
            }
        }]
        let labelCol = {
            sm: { span: 6 },
            xl: { span: 6 },
            xxl: { span: 5 },
        };

        let wrapperCol = {
            sm: { span: 18 },
            xl: { span: 18 },
            xxl: { span: 19 },
        };

        // Excel头部标题
        const header = [
            {
                title: '序号',
                dataIndex: 'key',
                key: 'key',
            }, {
                title: '学校',
                dataIndex: 'schoolname',
                key: 'schoolname',
            }, {
                title: '区县',
                dataIndex: 'departmentName',
                key: 'departmentName',
            }, {
                title: '隐患发现数(个)',
                dataIndex: 'dangernum',
                key: 'dangernum',
            }, {
                title: '隐患处理数(个)',
                dataIndex: 'dangerdealnum',
                key: 'dangerdealnum',
            }, {
                title: '隐患结案率(%)',
                dataIndex: 'dangerdealrate',
                key: 'dangerdealrate',
            }, {
                title: '隐患积分(分)',
                dataIndex: 'dangerdealpoints',
                key: 'dangerdealpoints',
            }
        ]


        return (
            <div style={{ marginBottom: 16 }}>
                <Form style={{
                    padding: '12px',
                    backgroundColor: '#fafafa',
                    borderRadius: 8,
                    marginBottom: 16,
                }}
                    layout="inline"
                    onSubmit={this.searchSubmit}>
                    <Row>
                        <Col span={8}>
                            <FormItem
                                label="截止日期"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("deadline", {
                                    rules: [{
                                        type: 'array',
                                        required: false,
                                    }],
                                    initialValue: [ // 核心代码
                                        moment(this.getBeforeWeekTime(), dateFormat),
                                        moment(this.getBeforeDayTime(), dateFormat),
                                      ],
                                })(
                                    <RangePicker
                                        style={{ width: '100%' }}
                                        format="YYYY-MM-DD"
                                        onChange={this.handleSelectTime} />
                                )}
                            </FormItem>
                        </Col>
                        {sessionStorage.getItem("departmentType") == "教育局" ? (
                            <Col span={5}>
                            <FormItem
                                label="区县"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("county", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请选择区县"
                                        onSelect = {(e) => {
                                            if(e < 0){
                                                this.getSchoolLevelByEduId(parseInt(sessionStorage.getItem("departmentId")), 1)
                                            }else {
                                                this.getSchoolLevelByEduId(e, 0)
                                            }
                                        }}>
                                        {countyOptions}
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        )
                        :null
                        }
                        <Col span={8}>
                            <FormItem
                                label="学校类型"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("schoolLevel", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请选择学校类型">
                                        {schoolLevelOptions}
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8}>
                        <FormItem
                                label="数值"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("average", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请选择数值情况">
                                        <Option value={0} key={0}>所有</Option>
                                        <Option value={1} key={1}>低于平均值</Option>
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        <Col>
                            <FormItem
                                style={{ float: 'right' }}>
                                <Button type="primary" htmlType="submit">搜索</Button>
                                <Button style={{ marginLeft: 8 }} onClick={this.searchReset}>清空</Button>
                                <Button type="primary" style={{ marginLeft: 8 }} onClick={() =>  {
                                    exportExcel(header, this.state.columnData, "学校隐患积分排名.xlsx")
                                    }}>导出Excel
                                </Button> 
                            </FormItem>
                        </Col>
                    </Row>
                </Form>
                <div>
                    {
                        this.state.isSearch ?
                            (
                                <div style={{
                                    marginBottom: 16,
                                    padding: 16,
                                    width: '100%',
                                    height: 350,
                                    border: '1px solid',
                                    borderColor: '#f5f5f5'
                                }}>
                                    <Skeleton loading={this.state.searchChartLoading} active>
                                        <ChartSearchDngerDealRate
                                            that={this}
                                            schoolName={this.state.schoolName}
                                            schoolResult={this.state.schoolResult}
                                            serialList={this.state.serialList}
                                            chartAvg={this.state.chartAvg}
                                            divId={'chartSearch'} />
                                    </Skeleton>
                                </div>
                            ) : null
                    }
                    {
                        this.state.isSearch ? 
                        (
                            <Alert
                            message="学校隐患积分说明"
                            description={"学校隐患积分=在统计时间范围内，该学校已处理的隐患数*10"}
                            type="info"
                            showIcon/>
                        ) : null
                    }
                    <Table
                        dataSource={this.state.columnData}
                        columns={columnsSearch}
                        loading={this.state.tableLoading}
                        locale={{ emptyText: '暂无数据' }}
                        onChange={this.handleChange2}
                        rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                        pagination={{  //分页
                            total: this.state.searchData.length, //数据总数量
                            defaultPageSize: 10, //默认显示几条一页
                            //pageSize: 10,
                            showTotal: function (total) {  //设置显示一共几条数据
                                return '共 ' + total + ' 条数据';
                            },
                            showSizeChanger: true,
                            showQuickJumper: true,
                            pageSizeOptions: [5, 10, 20, 30]
                        }} />
                        
                {
                    this.state.detailExist ? (
                        <DangerConditionDetail
                            visible={this.state.detailVisible}
                            currentSchoolId={this.state.currentSchoolId}
                            startTime={this.state.startTime}
                            endTime={this.state.endTime}
                            that={this}
                            flag={this.state.flag} />
                    ) : null
                }
                </div>
            </div>
        );
    }
}
const EduDangerDealRateRank = Form.create()(eduDangerDealRateRank);

//安全隐患排名查看详情划窗
class dangerConditionDetail extends Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: props.visible,
            that: props.that,
            currentSchoolId: props.currentSchoolId,
            startTime:props.startTime,
            endTime:props.endTime,
            flag:props.flag,
            updateVisible: false,
            detailVisible: false,
            alertVisible: false, //提示
            confirmLoading: false,
            previewVisible: false,
            previewImage: '',
            msg: "", //提交失败时的提示语
            tableLoading: true,
            data: [],
            filteredInfo: null,
            sortedInfo: null,
            // searchTextAddress: '',
            // searchTextReporter: '',
           
            allCategory: [],
            allStatus: [],
            isSearch: false,
            realNameArr: [], //上报人的autocomplete数据
            existCategory: [],
            searchData: [],
            test:true,
            searchChartLoading: true,
            chartSafetySceneSearchData: {}
        };
        //console.log('currentInspectPlanIds', props.currentInspectPlanIds)
    }

    componentDidMount() {
        this.refreshData(this.props.currentSchoolId);
    }

    componentWillReceiveProps(props) {
        this.setState({
            currentSchoolId: props.currentSchoolId,
            visible: props.visible,
            that: props.that,
            startTime:props.startTime,
            endTime:props.endTime,
        });
        if (props.visible && props.flag) {
            
            if(this.state.currentSchoolId != props.currentSchoolId) {
                this.refreshData(props.currentSchoolId);
            }
        }
    }
  
 

    refreshData(currentSchoolId) {
        console.log("111111111111", currentSchoolId);
        this.setState({
            confirmLoading: true,
            tableLoading: true
        })
        
        let columnData = [];
        let statusData = [];
        
        let values = {
            address: undefined,
            categoryId: undefined, 
            safetyLevel: undefined,
            name: undefined,
            status: undefined,
            // reportStartDate: moment().subtract(7, 'days').format('YYYY-MM-DD'),
            // reportEndDate: moment().subtract(1, 'days').format('YYYY-MM-DD'),
            reportStartDate: moment(this.state.startTime).format('YYYY-MM-DD'),
            reportEndDate: moment(this.state.endTime).format('YYYY-MM-DD'),
            dealStartDate: undefined,
            dealEndDate: undefined,
            dealName: undefined
        }

        getSafetySceneSearchApi(currentSchoolId, values)
                    .then((res) => {
                        res.data.forEach((item, index) => {
                            columnData.push({
                                key: index + 1,
                                id: item.id,
                                safetyLevel: item.safetyLevel,
                                address: item.address,
                                reporterId: item.reporter,
                                reporterName: item.reportName,
                                status: item.statusString,
                                createTime: item.createTime,
                                modifyTime: item.modifyTime,
                                categoryId: item.categoryId,
                                categoryName: item.categoryName,
                                dealName: item.dealName
                            });
                            statusData.push(item.statusString);
                        });

                        this.setState({
                            columnData: columnData,
                            tableLoading: false,
                            preData: columnData
                        });
                        let statusDataUnique = statusData.filter(function (element, index, array) {
                            return array.indexOf(element) === index;
                        });
                        let allStatus = statusDataUnique.map((d, index) => {
                            return ({
                                text: d,
                                value: d,
                            })
                        })
                        this.setState({
                            allStatus: allStatus,
                        });
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });

        // safetysceneBySchoolApi(currentSchoolId)
        //     .then((res) => {
        //         res.data.forEach((item, index) => {
        //             columnData.push({
        //                 key: index + 1,
        //                 id: item.id,
        //                 safetyLevel: item.safetyLevel,
        //                 address: item.address,
        //                 reporterId: item.reporter,
        //                 reporterName: item.reportName,
        //                 status: item.statusString,
        //                 createTime: item.createTime,
        //                 modifyTime: item.modifyTime,
        //                 categoryId: item.categoryId,
        //                 categoryName: item.categoryName,
        //                 dealName: item.dealName
        //             });
        //             statusData.push(item.statusString);
        //         });
        //         this.setState({
        //             columnData: columnData,
        //             tableLoading: false,
        //             preData: columnData
        //         });
        //         let statusDataUnique = statusData.filter(function (element, index, array) {
        //             return array.indexOf(element) === index;
        //         });
        //         let allStatus = statusDataUnique.map((d, index) => {
        //             return ({
        //                 text: d,
        //                 value: d,
        //             })
        //         })
        //         this.setState({
        //             allStatus: allStatus,
        //         });
        //     })
        //     .catch((e) => {
        //         if (e.response) {
        //             //请求已发出，服务器返回状态码不是2xx。
        //             console.info(e.response.data)
        //             console.info(e.response.status)
        //             console.info(e.response.headers)
        //         } else if (e.request) {
        //             // 请求已发出，但没有收到响应
        //             // e.request 在浏览器里是一个XMLHttpRequest实例，
        //             // 在node中是一个http.ClientRequest实例
        //             console.info(e.request)
        //         } else {
        //             //发送请求时异常，捕捉到错误
        //             console.info('error', e.message)
        //         }
        //         console.info(e.config)
        //     });

        allInspectItemCategory(currentSchoolId, 4)
            .then((res) => {
                //console.log(res.data);
                let categories = [];
                res.data.forEach((item, index) => {
                    let temp = {
                        text: item.category,
                        value: item.category,
                    }
                    categories.push(temp);
                });
                this.setState({
                    allCategory: categories,
                })
            }).catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

        getExistCategoryBySchoolIdAip(currentSchoolId)
            .then((res) => {
                this.setState({
                    existCategory: res.data,
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

        allUserApi(4, currentSchoolId)
            .then((res) => {
                let realNameArr = [];
                res.data.forEach((item, index) => {
                    //console.log("getAllUser", item);
                    realNameArr.push(item.realName);
                });
                this.setState({
                    realNameArr: realNameArr
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            }); 
    }


    formatTime(date) {
        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const day = date.getDate();
        const hour = date.getHours();
        const minute = date.getMinutes();
        const second = date.getSeconds();
        return [year, month, day].map(this.formatNumber).join('-') + ' ' + [hour, minute, second].map(this.formatNumber).join(':');
    }

    formatNumber(n) {
        n = n.toString();
        return n[1] ? n : '0' + n;
    }


    showDetailModal(id, safetyLevel, address, reporterName, status,
        createTime, modifyTime, categoryName) {
        let level = "";
        switch (safetyLevel) {
            case 1: level = "安全"; break;
            case 2: level = "一般"; break;
            case 3: level = "危险"; break;
            case 4: level = "非常危险"; break;
            case 5: level = "巡检排查"; break;
        }
        this.setState({
            detailVisible: true,
            currentId: id,
            currentSafetyLevel: level,
            currentAddress: address,
            currentReporterName: reporterName,
            currentStatus: status,
            currentCreateTime: createTime,
            currentModifyTime: modifyTime,
            currentCategoryName: categoryName,
        })
    }

    //关闭 alert 的提示
    handleClose() {
        this.setState({ alertVisible: false });
    }
    //关闭模态框
    handleUpdateCancel() {
        let val = this.refs.updateSafetysceneFormValue;
        val.resetFields();
        this.setState({
            alertVisible: false,
            updateVisible: false,
        });
    }
    //关闭模态框
    handleDetailCancel() {
        this.setState({
            alertVisible: false,
            detailVisible: false,
        });
    }

    clearAll = () => {
        this.setState({
            filteredInfo: null,
            sortedInfo: null,
        });

    }

    handleChange = (pagination, filters, sorter) => {
        //console.log('Various parameters', pagination, filters, sorter);
        this.setState({
            filteredInfo: filters,
            sortedInfo: sorter,
        });
    }

    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
        // this.setState({
        //     searchTextAddress: selectedKeys[0],
        //     searchTextReporter: selectedKeys[0]
        // });
    }

    handleSearchReset = clearFilters => () => {
        clearFilters();
        // this.setState({
        //     searchTextAddress: '',
        //     searchTextReporter: '',
        // });
    }

    getBeforeDayTime() {
        var time = (new Date()).getTime() - 24 * 60 * 60 * 1000;
        var beforeday = new Date(time); // 获取的是前一天日期

        // beforeday = beforeday.getFullYear() + "-" + (beforeday.getMonth() + 1 > 9
        //     ? (beforeday.getMonth() + 1) : "0" + (beforeday.getMonth()+1)) + "-" + (beforeday.getDate() > 9
        //         ? (beforeday.getDate()) : "0" + (beforeday.getDate())); //字符串拼接转格式：例如2018-08-19
        beforeday=this.state.startTime;
        return beforeday
    }
    getBeforeWeekTime() {
        var time = (new Date()).getTime() - 24 * 60 * 60 * 1000 * 7;
        var beforeweek = new Date(time); // 获取的是前一周日期

        beforeweek = beforeweek.getFullYear() + "-" + (beforeweek.getMonth() + 1 > 9
            ? (beforeweek.getMonth() + 1) : "0" + (beforeweek.getMonth() + 1)) + "-" + (beforeweek.getDate() > 9
                ? (beforeweek.getDate()) : "0" + (beforeweek.getDate())); //字符串拼接转格式：例如2018-08-19
        return beforeweek
    }

    searchSubmit = (e) => {
   
    
        e.preventDefault();
       
        this.props.form.validateFields((err, values) => {
            
           
            console.log('Received values of form: ', values);
            if (values.address == undefined && values.categoryId == undefined && values.safetyLevel == undefined
                && values.reporterName == undefined && values.status == undefined && values.createTime == undefined
                && values.modifyTime == undefined && values.dealName == undefined) {
                message.error('请至少填写一项条件再进行搜索');
             
            } else {
                this.setState({
                    tableLoading: true,
                    isSearch: true,
                    
                    
                });
              
                if (values.categoryId !== undefined && values.categoryId.length == 0) {
                    values.categoryId = undefined;
                }

                if (values.safetyLevel !== undefined && values.safetyLevel.length == 0) {
                    values.safetyLevel = undefined;
                }

                if (values.createTime == undefined || values.createTime.length == 0) {
                    values.reportStartDate = undefined;
                    values.reportEndDate = undefined;
                } else {
                    values.reportStartDate = moment(values.createTime[0]).format('YYYY-MM-DD');
                    values.reportEndDate = moment(values.createTime[1]).format('YYYY-MM-DD');
                }

                if (values.modifyTime == undefined || values.modifyTime.length == 0) {
                    values.dealStartDate = undefined;
                    values.dealEndDate = undefined;
                } else {
                    values.dealStartDate = moment(values.modifyTime[0]).format('YYYY-MM-DD');
                    values.dealEndDate = moment(values.modifyTime[1]).format('YYYY-MM-DD');
                }

                let columnData = [];
                let statusData = [];
                getSafetySceneSearchApi(this.state.currentSchoolId, values)
                    .then((res) => {
                        res.data.forEach((item, index) => {
                            columnData.push({
                                key: index + 1,
                                id: item.id,
                                safetyLevel: item.safetyLevel,
                                address: item.address,
                                reporterId: item.reporter,
                                reporterName: item.reportName,
                                status: item.statusString,
                                createTime: item.createTime,
                                modifyTime: item.modifyTime,
                                categoryId: item.categoryId,
                                categoryName: item.categoryName,
                                dealName: item.dealName
                            });
                            statusData.push(item.statusString);
                        });

                        this.setState({
                            columnData: columnData,
                            tableLoading: false
                        });
                        this.setState({
                            columnData: columnData,
                            tableLoading: false
                        });
                        let statusDataUnique = statusData.filter(function (element, index, array) {
                            return array.indexOf(element) === index;
                        });
                        let allStatus = statusDataUnique.map((d, index) => {
                            return ({
                                text: d,
                                value: d,
                            })
                        })
                        this.setState({
                            allStatus: allStatus,
                        });
                     
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });

                getSafetySceneSearchChartDataApi(this.state.currentSchoolId, values)
                    .then(res => {
                        console.log(res.data)
                        this.setState({
                            searchChartLoading: false,
                            chartSafetySceneSearchData: res.data,
                            alertVisible: false,
                        });
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // ��node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });
            }
        });
    }

    searchReset = () => {
        this.props.form.resetFields();
        this.setState({
            isSearch: false,
            columnData: this.state.preData,
        })
    }

    setFullScreen(opts) {
        this.setState({
            fullScreenVisible: true,
        })
        let fullchart = echarts.init(document.getElementById('fullScreen'))
        fullchart.setOption(opts);
    }

    fullScreenCancel() {
        this.setState({
            fullScreenVisible: false,
        })
    }

    render() {
        
        const Panel = Collapse.Panel;
        const gridStyle = {
            width: '33.33333333333333333333333%',
            height: '150px',
            textAlign: 'center',
            position: 'relative'
        };

        const { getFieldDecorator, getFieldValue } = this.props.form;
        let { sortedInfo, filteredInfo } = this.state;
        sortedInfo = sortedInfo || {};
        filteredInfo = filteredInfo || {};

        let keyWidth = undefined;
        let categoryNameWidth = undefined;
        let reporterNameWidth = undefined;
        let statusWidth = undefined;
        let actionWidth = undefined;
        let timeWidth = undefined;

        let winWidth;
        // 获取窗口宽度
        if (window.innerWidth)
            winWidth = window.innerWidth;
        else if ((document.body) && (document.body.clientWidth))
            winWidth = document.body.clientWidth;
        if (winWidth < 1500) {
            keyWidth = 60;
            categoryNameWidth = 110;
            reporterNameWidth = 90;
            statusWidth = 80;
            actionWidth = 110;
            timeWidth = 120;
        }

        const columns = [{
            title: "序号",
            dataIndex: "key",
            key: "key",
            width: keyWidth,
        }, {
            title: "地址",
            dataIndex: "address",
            key: "address",
            filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                <div className="custom-filter-dropdown">
                    <Input
                        ref={ele => this.searchInput = ele}
                        value={selectedKeys[0]}
                        onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                        onPressEnter={this.handleSearch(selectedKeys, confirm)}
                    />
                    <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                    <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                </div>
            ),
            filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
            onFilter: (value, record) => record.address.toLowerCase().includes(value.toLowerCase()),
            onFilterDropdownVisibleChange: (visible) => {
                if (visible) {
                    setTimeout(() => {
                        this.searchInput.focus();
                    });
                }
            }
        }, {
            title: "项目类别",
            dataIndex: "categoryName",
            key: "categoryName",
            width: categoryNameWidth,
            filters: this.state.allCategory,
            filteredValue: filteredInfo.categoryName || null,
            onFilter: (value, record) => record.categoryName.includes(value),
            filterIcon: filtered =>
                <Icon
                    type="filter"
                    style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
        }, {
            title: "安全等级",
            dataIndex: "safetyLevel",
            key: "safetyLevel",
            sorter: (a, b) => a.safetyLevel - b.safetyLevel,
            sortOrder: sortedInfo.columnKey === 'safetyLevel' && sortedInfo.order,
            render: (text) => (
                <div style={{ width: '90px' }}>
                    <img
                        style={{ width: '100%' }}
                        src={require('../img/safetyLevel' + text + '.png')} />
                </div>
            )
        }, {
            title: "上报人",
            dataIndex: "reporterName",
            key: "reporterName",
            width: reporterNameWidth,
            filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                <div className="custom-filter-dropdown">
                    <Input
                        ref={ele => this.searchInput = ele}
                        value={selectedKeys[0]}
                        onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                        onPressEnter={this.handleSearch(selectedKeys, confirm)}
                    />
                    <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                    <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                </div>
            ),
            filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
            onFilter: (value, record) => record.reporterName.toLowerCase().includes(value.toLowerCase()),
            onFilterDropdownVisibleChange: (visible) => {
                if (visible) {
                    setTimeout(() => {
                        this.searchInput.focus();
                    });
                }
            }
        }, {
            title: "状态",
            dataIndex: "status",
            key: "status",
            width: statusWidth,
            filters: this.state.allStatus,
            filteredValue: filteredInfo.status || null,
            onFilter: (value, record) => record.status.includes(value),
            filterIcon: filtered => <Icon type="filter" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
            render: (text) => {
                if (text == '已处理') { return (<span style={{ color: 'green' }}>已处理</span>) }
                else if (text == '未处理') { return (<span style={{ color: 'red' }}>未处理</span>) }
                else if (text == '处理中') { return (<span style={{ color: '#096dd9' }}>处理中</span>) }
            },
        }, {
            title: "上报时间",
            dataIndex: "createTime",
            key: "createTime",
            width: timeWidth,
            sorter: (a, b) => new Date(a.createTime).getTime() - new Date(b.createTime).getTime(),
            sortOrder: sortedInfo.columnKey === 'createTime' && sortedInfo.order,
        }, {
            title: "处理时间",
            dataIndex: "modifyTime",
            key: "modifyTime",
            width: timeWidth,
            sorter: (a, b) => new Date(a.modifyTime).getTime() - new Date(b.modifyTime).getTime(),
            sortOrder: sortedInfo.columnKey === 'modifyTime' && sortedInfo.order,
            render: (text, record) => {
                if (record.status == '已处理') { return (<span>{text}</span>) }
                else if (record.status == '未处理') { return (<span>-</span>) }
            },
        }, {
            title: "处理人",
            dataIndex: "dealName",
            key: "dealName",
            width: reporterNameWidth,
            filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                <div className="custom-filter-dropdown">
                    <Input
                        ref={ele => this.searchInput = ele}
                        value={selectedKeys[0]}
                        onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                        onPressEnter={this.handleSearch(selectedKeys, confirm)}
                    />
                    <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                    <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                </div>
            ),
            filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
            onFilter: (value, record) => record.reporterName.toLowerCase().includes(value.toLowerCase()),
            onFilterDropdownVisibleChange: (visible) => {
                if (visible) {
                    setTimeout(() => {
                        this.searchInput.focus();
                    });
                }
            },
            render: (text, record) => {
                if (record.status == '未处理') { return (<span>-</span>) }
                else {
                    return (<span>{text}</span>)
                }
            }
        }, {
            title: "操作详情",
            key: "action",
            width: actionWidth,
            render: (text, record) => {
                    return (
                        <span>
                            <a href="javascript:;" onClick={this.showDetailModal.bind(this,
                                record.id, record.safetyLevel, record.address,
                                record.reporterName, record.status, record.createTime,
                                record.modifyTime, record.categoryName)}>详细</a>
                        </span>
                    )
            }
        }];

        let categoryOptions;
        if (this.state.existCategory.length != 0) {
            categoryOptions = this.state.existCategory.map((d, index) =>
                <Option value={d.id} key={index}>{d.category}</Option>
            );
        }

        let statusOptions;
        if (this.state.allStatus.length != 0) {
            statusOptions = this.state.allStatus.map((d, index) =>
                <Option value={d.value} key={index}>{d.value}</Option>
            );
        }

        let labelCol = {
            sm: { span: 6 },
            xl: { span: 6 },
            xxl: { span: 5 },
        };

        let wrapperCol = {
            sm: { span: 18 },
            xl: { span: 18 },
            xxl: { span: 19 },
        };

        return (
            <div>
                <Drawer
                    bodyStyle={{ paddingBottom: 80 }}
                    width={0.85*window.screen.width}
                    title='安全隐患详情'
                    visible={this.state.visible}
                    onClose={this.state.that.handleDetailDrawerCancel.bind(this.state.that)}
                    destroyOnClose={true}
                    closable
                >

                <div style={{ marginBottom: 16 }}>
                <Form
                    style={{
                        padding: '12px',
                        backgroundColor: '#fafafa',
                        borderRadius: 8,
                        marginBottom: 16
                    }}
                    layout="inline"
                    onSubmit={this.searchSubmit}>
                    <Row>
                        <Col span={8}>
                            <FormItem
                                label="地址"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("address", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Input
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请输入地址"
                                    ></Input>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8}>
                            <FormItem
                                label="项目类别"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("categoryId", {
                                    rules: [{
                                        type: 'array',
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        style={{ width: '100%' }}
                                        mode="multiple"
                                        placeholder="请选择项目类别(可多选)">
                                        {categoryOptions}
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8}>
                            <FormItem
                                label="安全等级"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("safetyLevel", {
                                    rules: [{
                                        type: 'array',
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        style={{ width: '100%' }}
                                        mode="multiple"
                                        placeholder="请选择安全等级(可多选)">
                                        <Option value={1}>安全</Option>
                                        <Option value={2}>一般</Option>
                                        <Option value={3}>危险</Option>
                                        <Option value={4}>非常危险</Option>
                                        <Option value={5}>巡检排查</Option>
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={8}>
                            <FormItem
                                label="上报人"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("reporterName", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <AutoComplete
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        dataSource={this.state.realNameArr}
                                        placeholder="请输入上报人"
                                        filterOption={(inputValue, option) => option.props.children.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1}
                                    />
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8}>
                            <FormItem
                                label="上报时间"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("createTime", {
                                    rules: [{
                                        type: 'array',
                                        required: false,
                                    }],
                                    initialValue: [ // 核心代码
                                        moment(this.state.startTime, 'YYYY-MM-DD'),
                                        moment(this.state.endTime, 'YYYY-MM-DD'),
                                      ],
                                })(
                                    <RangePicker
                                        style={{ width: '100%' }}
                                        format="YYYY-MM-DD" />
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8}>
                            <FormItem
                                label="处理时间"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("modifyTime", {
                                    rules: [{
                                        type: 'array',
                                        required: false,
                                    }]
                                })(
                                    <RangePicker
                                        style={{ width: '100%' }}
                                        format="YYYY-MM-DD" />
                                )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={8}>
                            <FormItem
                                label="处理人"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("dealName", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <AutoComplete
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        dataSource={this.state.realNameArr}
                                        placeholder="请输入处理人"
                                        filterOption={(inputValue, option) => option.props.children.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1}
                                    />
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8}>
                            <FormItem
                                label="状态"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("status", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请选择状态">
                                        {statusOptions}
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        <FormItem
                            style={{ float: 'right' }}>
                            <Button type="primary" htmlType="submit" onClick={this.state.that.handleDetailDrawerClick.bind(this.state.that)}>搜索</Button>
                            <Button style={{ marginLeft: 8 }} onClick={this.searchReset}>清空</Button>
                        </FormItem>
                    </Row>
                </Form>
                {this.state.isSearch ? (
                    <div style={{
                        marginBottom: 16,
                        padding: 16,
                        width: '100%',
                        height: 300,
                        border: '1px solid',
                        borderColor: '#f5f5f5'
                    }}>
                        <Skeleton loading={this.state.searchChartLoading} active>
                            <ChartSafetySceneSearch
                                that={this}
                                chartData={this.state.chartSafetySceneSearchData} />
                        </Skeleton>
                    </div>
                ) : null}
                {/* <Button style={{ marginBottom: '20px' }} onClick={this.clearAll}>
                    <Icon type="delete" theme="outlined" />清除筛选与排序</Button> */}
                <Drawer
                    bodyStyle={{ paddingBottom: 80 }}
                    width={600}
                    title={'安全现场详细信息'}
                    visible={this.state.detailVisible}
                    onClose={this.handleDetailCancel.bind(this)}
                    destroyOnClose={true}
                    closable
                >
                    <SafetysceneDetail
                        currentId={this.state.currentId} currentSafetyLevel={this.state.currentSafetyLevel}
                        currentAddress={this.state.currentAddress} currentReporterName={this.state.currentReporterName}
                        currentStatus={this.state.currentStatus} currentCreateTime={this.state.currentCreateTime}
                        currentModifyTime={this.state.currentModifyTime} currentCategoryName={this.state.currentCategoryName} />
                    {
                        this.state.alertVisible ?
                            (
                                <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                            ) : null
                    }
                    <div
                        style={{
                            position: 'absolute',
                            left: 0,
                            bottom: 0,
                            width: '100%',
                            borderTop: '1px solid #e9e9e9',
                            padding: '10px 16px',
                            background: '#fff',
                            textAlign: 'right',
                        }}
                    >
                        <Button key="submit" type="primary" size="large" loading={this.state.confirmLoading}
                            onClick={this.handleDetailCancel.bind(this)}>关闭</Button>
                    </div>
                </Drawer>

                <Table
                    dataSource={this.state.columnData}
                    columns={columns}
                    loading={this.state.tableLoading}
                    locale={{ emptyText: '暂无数据' }}
                    rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                    onChange={this.handleChange}
                    pagination={{  //分页
                        total: this.state.data.length, //数据总数量
                        defaultPageSize: 10, //默认显示几条一页
                        //pageSize: 10,
                        showTotal: function (total) {  //设置显示一共几条数据
                            return '共 ' + total + ' 条数据';
                        },
                        showSizeChanger: true,
                        showQuickJumper: true,
                        pageSizeOptions: [5, 10, 20, 30]
                    }} />

                <Modal
                    destroyOnClose
                    visible={this.state.fullScreenVisible}
                    title={'每日隐患上报/处理情况展示图'}
                    footer={null}
                    width={1000}
                    bodyStyle={{
                        padding: 24,
                        height: 600
                    }}
                    onCancel={() => { this.fullScreenCancel() }}>
                    <div id='fullScreen'
                        style={{
                            width: '100%',
                            height: '100%',
                        }} />

                </Modal>
                </div>
                    
                    <div
                        style={{
                            position: 'absolute',
                            left: 0,
                            bottom: 0,
                            width: '100%',
                            borderTop: '1px solid #e9e9e9',
                            padding: '10px 16px',
                            background: '#fff',
                            textAlign: 'right',
                        }}
                    >
                        <Button size="large" onClick={this.state.that.handleDetailDrawerCancel.bind(this.state.that)}
                            style={{ marginRight: 20 }}>关闭</Button>
                    </div>
                </Drawer>
                
            </div>

        );
    }
}
const DangerConditionDetail = Form.create()(dangerConditionDetail);

class ChartSafetySceneSearch extends Component {
    constructor(props) {
        super(props);

        this.state = {
            chartData: props.chartData,
            that: props.that,
        };
    }

    componentWillReceiveProps(props) {
        if (JSON.stringify(props.chartData) !== JSON.stringify(this.state.chartData)) {
            this.setState({
                chartData: props.chartData,
                that: props.that,
            }, () => {
                this.drawChart();
            })
        }
    }

    componentDidMount() {
        this.drawChart();
    }

    drawChart() {
        if (JSON.stringify(this.state.chartData) != '{}') {
            // console.log(this.state.chartData);
            let chart = echarts.init(document.getElementById('chartSafetySceneSearch'));

            let dataZoom;
            if (this.state.chartData.date.length <= 30) {
                dataZoom = [{
                    type: 'inside',
                    start: 0,
                    end: 100
                }, {
                    start: 0,
                    end: 100,
                    handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                    handleSize: '80%',
                    handleStyle: {
                        color: '#fff',
                        shadowBlur: 3,
                        shadowColor: 'rgba(0, 0, 0, 0.6)',
                        shadowOffsetX: 2,
                        shadowOffsetY: 2
                    }
                }];
            } else {
                dataZoom = [{
                    type: 'inside',
                    start: (this.state.chartData.date.length - 30) / this.state.chartData.date.length * 100,
                    end: 100,
                }, {
                    start: (this.state.chartData.date.length - 30) / this.state.chartData.date.length * 100,
                    end: 100,
                    handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                    handleSize: '80%',
                    handleStyle: {
                        color: '#fff',
                        shadowBlur: 3,
                        shadowColor: 'rgba(0, 0, 0, 0.6)',
                        shadowOffsetX: 2,
                        shadowOffsetY: 2
                    }
                }];
            }


            chart.setOption({
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: ['上报数', '处理数']
                },
                grid: {
                    left: '5%',
                    right: '5%',
                    bottom: '40px',
                    top: '30px',
                    containLabel: true
                },
                toolbox: {
                    feature: {
                        saveAsImage: { show: true, },
                        // restore: { show: true },
                        // dataView: { show: true, readOnly: false },
                        magicType: { show: true, type: ['line', 'bar'] },
                        myFullScreen: {
                            show: true,
                            title: '全屏查看',
                            icon: 'path://M160.762 757.972l210.611-210.61 105.66 105.659-210.644 210.643L362.667 960H64V661.15l96.762 96.822zM266.39 160.336L477.032 370.98 371.373 476.64l-210.61-210.61L64 362.848V64h298.667l-96.278 96.336z m491.222 703.328L546.968 653.02l105.659-105.66 210.61 210.61L960 661.152V960H661.333l96.278-96.336z m105.627-597.636l-210.611 210.61-105.66-105.659 210.644-210.643L661.333 64H960v298.85l-96.762-96.822z',
                            onclick: (e) => {
                                var opts = e.getOption()
                                opts.toolbox[0].feature.myFullScreen.show = false;
                                console.log(this.state)
                                this.state.that.setFullScreen(opts);

                            }
                        }
                    }
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: this.state.chartData.date,
                    axisTick: {
                        alignWithLabel: true
                    },
                },
                yAxis: {
                    name: '数量',
                    type: 'value'
                },
                dataZoom: dataZoom,
                series: [{
                    name: '上报数',
                    type: 'line',
                    data: this.state.chartData.reportNum,
                    smooth: true,
                    symbol: 'none',
                    sampling: 'average',
                }, {
                    name: '处理数',
                    type: 'line',
                    data: this.state.chartData.dealNum,
                    smooth: true,
                    symbol: 'none',
                    sampling: 'average',
                }]

            });
            window.onresize = chart.resize;
        }

    }

    render() {
        let chartStyle = {
            height: '100%',
            width: '100%',
        };
        return (<div id='chartSafetySceneSearch' style={chartStyle} />)
    }
}

class SafetysceneDetail extends Component {
    constructor(props) {
        super(props);
        this.state = {
            currentId: props.currentId,
            currentSafetyLevel: props.currentSafetyLevel,
            currentAddress: props.currentAddress,
            currentReporterName: props.currentReporterName,
            currentStatus: props.currentStatus,
            currentCreateTime: props.currentCreateTime,
            currentModifyTime: props.currentModifyTime,
            currentCategoryName: props.currentCategoryName,

            currentContent: '',
            currentPhoto: [],
            currentVideo: '',
            currentPhotoStr: '',
            currentDealContent: '',
            currentDealPhoto: [],
            currentDealVideo: '',
            currentDealPhotoStr: '',
            currentDealUserName: '',
            currentEvaluate: 0,

            previewVisible: false,
            previewImage: '',
        };
    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        //console.log(this.state);
        safetysceneDetailByIdApi(this.state.currentId)
            .then((res) => {
                //console.log(res);
                if (this.state.currentStatus == '已处理') {
                    this.setState({
                        currentContent: res.data.content,
                        currentPhoto: res.data.photoList,
                        currentVideo: res.data.video,
                        currentDealContent: res.data.dealContent,
                        currentDealPhoto: res.data.dealPhotoList,
                        currentDealVideo: res.data.dealVideo,
                        currentDealUserName: res.data.realName,
                        currentEvaluate: res.data.evaluate,
                        currentPhotoStr: res.data.photo,
                        currentDealPhotoStr: res.data.dealPhoto
                    });
                } else if (this.state.currentStatus == '未处理') {
                    this.setState({
                        currentContent: res.data.content,
                        currentPhoto: res.data.photoList,
                        currentVideo: res.data.video,
                        currentPhotoStr: res.data.photo,
                    });
                } else if (this.state.currentStatus == '处理中') {
                    this.setState({
                        currentContent: res.data.content,
                        currentPhoto: res.data.photoList,
                        // currentDealContent: res.data.dealContent,
                        // currentDealPhoto: res.data.dealPhotoList,
                        currentDealUserName: res.data.realName,

                        currentPhotoStr: res.data.photo,
                        currentDealPhotoStr: res.data.dealPhoto
                    });
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }


    handlePreview = (src) => {
        this.setState({
            previewImage: src,
            previewVisible: true,
        });
    }
    //查看video
    handlePreview2 = (src) => {

    }

    handleCancel = () => this.setState({ previewVisible: false })

    render() {
        const gridStyle = {
            width: '33.33333333333333333333333%',
            height: '150px',
            textAlign: 'center',
            padding: '10px',
            position: 'relative'
        };

        let prePhotos;
        let preVideo;
        if (this.state.currentPhotoStr == '') {
            prePhotos = (
                <Card.Grid
                    key={0}
                    style={gridStyle}>
                    <img
                        style={{
                            width: 'auto',
                            height: 'auto',
                            position: 'absolute',
                            top: 0,
                            left: 0,
                            right: 0,
                            bottom: 0,
                            margin: 'auto',
                            maxWidth: '100%',
                            maxHeight: '100%',
                            padding: 5,
                        }}
                        alt="上报照片"
                        src={require('../img/nophoto.png')} />
                </Card.Grid>
            );
        } else {
            prePhotos = this.state.currentPhoto.map((d, index) =>
                <Card.Grid
                    key={index}
                    style={gridStyle}>
                        {/* <RViewerJS> */}
                        <img
                        style={{
                            width: 'auto',
                            height: 'auto',
                            position: 'absolute',
                            top: 0,
                            left: 0,
                            right: 0,
                            bottom: 0,
                            margin: 'auto',
                            maxWidth: '100%',
                            maxHeight: '100%',
                            padding: 5,
                        }}
                        alt="上报照片"
                        src={UrlPrefix + d}
                         />
                        {/* </RViewerJS> */}
                   
                </Card.Grid>
            );
        }
        preVideo = (
            <Card.Grid
                key={0}
                style={gridStyle}>
                <video
                    style={{
                        width: 'auto',
                        height: 'auto',
                        position: 'absolute',
                        top: 0,
                        left: 0,
                        right: 0,
                        bottom: 0,
                        margin: 'auto',
                        maxWidth: '100%',
                        maxHeight: '100%',
                        padding: 5,
                    }}
                    src={UrlPrefix + this.state.currentVideo} controls />
            </Card.Grid>
        );
        let preData = [{
            title: '上报地址',
            description: this.state.currentAddress,
        }, {
            title: '上报类别',
            description: this.state.currentCategoryName,
        }, {
            title: '安全等级',
            description: this.state.currentSafetyLevel,
        }, {
            title: '上报人',
            description: this.state.currentReporterName,
        }, {
            title: '状态',
            description: this.state.currentStatus,
        }, {
            title: '上报时间',
            description: this.state.currentCreateTime,
        }, {
            title: '上报内容',
            description: this.state.currentContent,
        }, {
            title: '上报照片',
            description: (
                <Card
                    hoverable
                    style={{ marginTop: '10px' }}>
                        <RViewerJS>
                    {prePhotos}
                    </RViewerJS>
                </Card>),
        }, {
            title: '上报视频',
            description: (
                this.state.currentVideo == "" ?
                    <span>暂无视频</span>
                    :
                    <Card
                        hoverable
                        style={{ marginTop: '10px' }}>
                            <RViewerJS>
                        {preVideo}
                        </RViewerJS>
                    </Card>
            ),
        }];

        let dealData;
        if (this.state.currentStatus == '已处理' || this.state.currentStatus == '处理中') {
            let dealPhotos;
            if (this.state.currentDealPhotoStr == '') {
                dealPhotos = (
                    <Card.Grid
                        key={0}
                        style={gridStyle}>
                        <img
                            style={{
                                width: 'auto',
                                height: 'auto',
                                position: 'absolute',
                                top: 0,
                                left: 0,
                                right: 0,
                                bottom: 0,
                                margin: 'auto',
                                maxWidth: '100%',
                                maxHeight: '100%',
                                padding: 5,
                            }}
                            alt="暂无图片"
                            src={require('../img/nophoto.png')} />
                    </Card.Grid>
                );
            } else {
                dealPhotos = this.state.currentDealPhoto.map((d, index) =>
                    <Card.Grid
                        key={index}
                        style={gridStyle}>
                            {/* <RViewerJS> */}
                            <img
                            style={{
                                width: 'auto',
                                height: 'auto',
                                position: 'absolute',
                                top: 0,
                                left: 0,
                                right: 0,
                                bottom: 0,
                                margin: 'auto',
                                maxWidth: '100%',
                                maxHeight: '100%',
                                padding: 5,
                            }}
                            alt="上报照片"
                            src={UrlPrefix + d}
                             />
                            {/* </RViewerJS> */}
                       
                    </Card.Grid>
                );
            }
            let dealVideo = (
                <Card.Grid
                    key={0}
                    style={gridStyle}>
                    <video
                        style={{
                            width: 'auto',
                            height: 'auto',
                            position: 'absolute',
                            margin: 'auto',
                            top: 0,
                            left: 0,
                            right: 0,
                            bottom: 0,
                            maxWidth: '100%',
                            maxHeight: '100%',
                            padding: 5,
                        }}
                        src={UrlPrefix + this.state.currentDealVideo} controls />
                </Card.Grid>
            );
            dealData = [{
                title: '处理时间',
                description: this.state.currentModifyTime,
            }, {
                title: '处理人员',
                description: this.state.currentDealUserName,
            }, {
                title: '处理内容',
                description: this.state.currentDealContent,
            }, {
                title: '处理照片',
                description: (
                    <Card
                        hoverable
                        style={{ marginTop: '10px' }}>
                            <RViewerJS>
                        {dealPhotos}
                        </RViewerJS>
                    </Card>),
            }, {
                title: '处理视频',
                description: (
                    this.state.currentDealVideo == "" ?
                        <span>暂无视频</span>
                        :
                        <Card
                            hoverable
                            style={{ marginTop: '10px' }}>
                                <RViewerJS>
                            {dealVideo}
                            </RViewerJS>
                        </Card>
                ),
            }]

            if (this.state.currentStatus === '已处理') {
                dealData.push({
                    title: '评价情况',
                    description: (
                        this.state.currentEvaluate === 0 ?
                            <span>暂未评价</span>
                            :
                            <Rate disabled defaultValue={this.state.currentEvaluate} />
                    )
                })
            }
        } else if (this.state.currentStatus == '未处理') {
            dealData = [{
                title: '此条暂未处理',
            }]
        }


        return (
            <div>
                <Tabs
                    defaultActiveKey="1">
                    <TabPane tab={<span ><IconFont type="icon-weiwancheng" className='iconTabs' />上报信息</span>} key="1">
                        <List
                            itemLayout="horizontal"
                            dataSource={preData}
                            renderItem={item => (
                                <List.Item>
                                    <List.Item.Meta
                                        title={item.title}
                                        description={item.description}
                                    />
                                </List.Item>
                            )}
                        />
                    </TabPane>
                    <TabPane tab={<span><IconFont type="icon-yiwanchengdingdan" className='iconTabs' />处理信息</span>} key="2">
                        <List
                            itemLayout="horizontal"
                            dataSource={dealData}
                            renderItem={item => (
                                <List.Item>
                                    <List.Item.Meta
                                        title={item.title}
                                        description={item.description}
                                    />
                                </List.Item>
                            )}
                        />
                    </TabPane>
                </Tabs>
                <Modal
                    destroyOnClose
                    visible={this.state.previewVisible}
                    footer={null}
                    bodyStyle={{
                        paddingTop: 48,
                    }}
                    onCancel={this.handleCancel}>
                    <img
                        alt="安全现场上报与处理照片"
                        style={{ width: '100%' }}
                        src={this.state.previewImage} />
                </Modal>
            </div>

        );
    }
}

//校隐患处理率排名柱状图
class ChartSearchDngerDealRate extends Component {
    constructor(props) {
        super(props);
        this.state = {
            schoolResult: props.schoolResult || [],
            //schoolResult: [[1281.0, 600.0, 72.0, 87, 94], [63.0, 0.0, -1.5, 98, 391]],
            schoolName: props.schoolName || [],
            //schoolName: [[" 丰惠镇中心幼儿园", "第二实验幼儿园盛丰园区", "第一实验幼儿园和润花园区", "第一实验幼儿园新上海园区", "梯度中学"], ["第一实验幼儿园新上海园区", "梯度中学", "上浦镇中心幼儿园", "第一实验幼儿园新上海园区", "梯度中学"]],
            serialList: props.serialList || [],
            //serialList: ["1", "2"],
            that: props.that,
            currentIndex: 0,
            divId: props.divId,
            data1: 0,
            schoolNamePart: [],
            chartAvg: props.chartAvg
        };

    }

    componentWillReceiveProps(props) {

        if (JSON.stringify(props.schoolName) != JSON.stringify(this.state.schoolName) && props.serialList.length > 0) {
            this.setState({
                that: props.that,
                schoolResult: props.schoolResult,
                schoolName: props.schoolName,
                serialList: props.serialList,
                chartAvg: props.chartAvg
            }, () => {
                this.drawChart()
            })
        }
    }

    componentDidMount() {
        let optionData = [];
        if (this.state.schoolName.length != 0) {
            this.drawChart();
        }
    }




    drawChart() {

        let optionData = [];

        let chart = echarts.init(document.getElementById('chartSearch'));
        let option = {

            baseOption: {
                timeline: {
                    axisType: 'category',
                    triggerEvent: true,
                    playInterval: 1000,
                    data: this.state.serialList
                },
                title: {
                    text: '学校隐患积分排名',
                    left: 'center',
                    top: '10px',
                    subtext:'平均值: ' + this.state.chartAvg +'分',
                    subtextStyle: {
                        fontSize: 16
                    }
                },
                color: ['#3398DB'],
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                        type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                    }
                },
                toolbox: {
                    show: true,
                    feature: {
                        dataZoom: {
                            yAxisIndex: 'none'
                        },
                        dataView: { readOnly: false },
                        magicType: { type: ['line', 'bar'] },
                        restore: {},
                        saveAsImage: {}
                    }
                },
                grid: {
                    left: '5%',
                    right: '5%',
                    bottom: '50px',
                    top: '90px',
                    containLabel: true
                },
                xAxis: [
                    {
                        type: 'category',
                        data: this.state.schoolNamePart,
                        axisTick: {
                            alignWithLabel: true
                        },
                        axisLabel: {
                            textStyle: {
                                fontSize: 16
                            }
                        }
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        axisLabel: {
                            formatter: '{value}分',
                            textStyle: {
                                fontSize: 16
                            }
                        }
                    }
                ],

                series: [
                    { name: '隐患处理率', type: 'bar' },
                ],

            },
            options: []
        };


        for (var i = 0; i < this.state.schoolResult.length; i++) {
            let schoolNameList = [];
            for(var j = 0;j < this.state.schoolName[i].length; j++){
                let arr = this.state.schoolName[i][j].split("\n");
                schoolNameList.push(arr[0]);
            }
            
            option.options.push({
                xAxis: {
                    data: sessionStorage.getItem("departmentType") == "教育局" ? this.state.schoolName[i]
                    : schoolNameList
                },
                series: [                
                    {
                        name: '隐患处理率',
                        type: 'bar',
                        data: this.state.schoolResult[i],
                        barGap: '100%',
                        barMaxWidth: 25,
                        animation: false,
                        itemStyle:
                            {
                                color: 'rgb(255, 70, 131)',
                                //color: '#FFD700',
                                normal: {
                                   // color: '#FFD700',
                                    label: {
                                        show: true, //开启显示
                                        position: 'top', //在上方显示
                                        textStyle: { //数值样式
                                            color: 'black',
                                            fontSize: 14
                                        }
                                    }
                                }
                            },
                        showBackground: true,
                        backgroundStyle: {
                            color: 'rgba(180, 180, 180, 0.2)'
                        },
                        // markLine: {
                        //     label: { formatter: '平均值: ' + this.state.chartAvg },
                        //     symbol: 'none',
                        //     data: [{
                        //         type: 'average',
                        //         name: '平均值',
                        //     }]
                        // },
            
                        markPoint: {
                            data: [
                                {
                                    type: 'max', name: '最大值'
                                }, {
                                    type: 'min', name: '最小值'
                                }
                            ]
                        }
                    }
                ]
            })
        }

        chart.setOption(option);
       
    }


    render() {
        let chartStyle = {
            height: '100%',
            width: '100%',
        };
        return (<div id={this.state.divId} style={chartStyle} />)
    }
}

//综合积分排名
class comprehensivePointsRank extends Component {
    constructor(props) {
        super(props);
        this.state = {
            alertVisible: false, //提示
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            tableLoading: true,
            filteredInfo: null,
            sortedInfo: null,
            searchData: [],
            schoolLevel: [],
            countyList: [],
            searchChartLoading: true,
            chartSearchData: {},
            chartSearchAvg: "",
            startTime: "",
            endTime: "",
            isSearch: false,
            departmentId: sessionStorage.getItem("departmentId")
        };
    }
    componentWillMount() {
    }
    componentDidMount() {
        this.refreshData();
    }
    getBeforeDayTime() {
        var time = (new Date()).getTime() - 24 * 60 * 60 * 1000;
        var beforeday = new Date(time); // 获取的是前一天日期

        beforeday = beforeday.getFullYear() + "-" + (beforeday.getMonth() + 1 > 9
            ? (beforeday.getMonth() + 1) : "0" + (beforeday.getMonth()+1)) + "-" + (beforeday.getDate() > 9
                ? (beforeday.getDate()) : "0" + (beforeday.getDate())); //字符串拼接转格式：例如2018-08-19
        
        return beforeday
    }
    getBeforeWeekTime() {
        var time = (new Date()).getTime() - 24 * 60 * 60 * 1000 * 7;
        var beforeweek = new Date(time); // 获取的是前一周日期

        beforeweek = beforeweek.getFullYear() + "-" + (beforeweek.getMonth() + 1 > 9
            ? (beforeweek.getMonth() + 1) : "0" + (beforeweek.getMonth() + 1)) + "-" + (beforeweek.getDate() > 9
                ? (beforeweek.getDate()) : "0" + (beforeweek.getDate())); //字符串拼接转格式：例如2018-08-19
        return beforeweek
    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        let columnData = [];
        let schoolLevel;
        var startTime = this.getBeforeWeekTime()
        var endTime = this.getBeforeDayTime()

        let departmentId = -sessionStorage.getItem("departmentId")

        getComprehensivePointsRankApi(departmentId, schoolLevel, startTime, endTime)
            .then((res) => {
                res.data.comprehensivePointsRankList.forEach((item, index) => {
                    columnData.push({
                        key: index + 1,
                        schoolname: item.schoolname,
                        comprehensivepoints: item.comprehensivepoints,
                        departmentName: item.departmentName,
                        inspectpoints: item.inspectpoints,
                        patrolpoints: item.patrolpoints,
                        dangerdealpoints: item.dangerdealpoints,
                        patrolpointsRank: item.patrolpointsRank,
                        inspectpointsRank: item.inspectpointsRank,
                        dangerdealpointsRank: item.dangerdealpointsRank
                    });
                });
                this.setState({
                    columnData: columnData,
                    startTime: startTime,
                    endTime: endTime,
                    tableLoading: false,
                    alertVisible: false,
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });


            getComprehensivePointsRankApi2(departmentId, schoolLevel, startTime, endTime)
            .then((res) => {
                if (res.data.serialList.length == 0) {
                    this.setState({
                        schoolResult: [],
                        schoolName: [],
                        serialList: [],
                        chartAvg: "",
                        tableLoading: false,
                        isSearch: false
                    });
                } else {
                    this.setState({
                        schoolResult: res.data.schoolResults,
                        schoolName: res.data.schoolNames,
                        serialList: res.data.serialList,
                        chartAvg: res.data.comprehensivepointsavg,
                        searchChartLoading: false,
                        tableLoading: false,
                        alertVisible: false,
                        isSearch: true
                    });
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });


        this.getSchoolLevelByEduId(sessionStorage.getItem("departmentId"), 1)
    

        getDepartmentApi(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                this.setState({
                    countyList: res.data
                });
            }).catch((e) => {
                console.log(e);
            })
    }

    searchSubmit = (e) => {
        var schoolLevel;
        var departmentId;
        e.preventDefault();
        this.props.form.validateFields((err, values) => {

            if (values.deadline == undefined && values.schoolLevel == undefined) {
                message.error('请至少填写一项条件再进行搜索');
            } else {
                if (values.schoolLevel != undefined) {
                    schoolLevel = values.schoolLevel
                }
                if(!isNaN(values.county)){
                    departmentId = values.county
                }else{
                    departmentId = -parseInt(sessionStorage.getItem("departmentId"))
                }
                this.setState({
                    tableLoading: true
                });
                let columnData = [];
                getComprehensivePointsRankApi(departmentId, schoolLevel, this.state.startTime, this.state.endTime)
                    .then((res) => {
                        res.data.comprehensivePointsRankList.forEach((item, index) => {
                            columnData.push({
                                key: index + 1,
                                schoolname: item.schoolname,
                                comprehensivepoints: item.comprehensivepoints,
                                departmentName: item.departmentName,
                                inspectpoints: item.inspectpoints,
                                patrolpoints: item.patrolpoints,
                                dangerdealpoints: item.dangerdealpoints,
                                patrolpointsRank: item.patrolpointsRank,
                                inspectpointsRank: item.inspectpointsRank,
                                dangerdealpointsRank: item.dangerdealpointsRank
                            });
                        });
                        this.setState({
                            columnData: columnData,
                            tableLoading: false,
                            alertVisible: false,
                        });
                        if(values.average == 1){
                            let columnDataAvg = [];
                            let columnDataTemp = this.state.columnData;
                            let sum = 0;
                            for(let i = 0;i < columnDataTemp.length; i++){
                                sum += parseFloat(columnDataTemp[i].comprehensivepoints);
                            }
                            let avg = sum / columnDataTemp.length;
                            let index = 1;
                            for(let i = 0;i < columnDataTemp.length;i ++){
                                if(parseFloat(columnDataTemp[i].comprehensivepoints) <= avg){
                                    columnDataTemp[i].key = index++;
                                    columnDataAvg.push(columnDataTemp[i]);
                                }
                            }
                            this.setState({
                                columnData: columnDataAvg
                            })
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });
                    getComprehensivePointsRankApi2(departmentId, schoolLevel, this.state.startTime, this.state.endTime)
                    .then((res) => {
                        if (res.data.serialList.length == 0) {
                            this.setState({
                                schoolResult: [],
                                schoolName: [],
                                serialList: [],
                                chartAvg: "",
                                tableLoading: false,
                                isSearch: false
                            });
                        } else {
                            this.setState({
                                schoolResult: res.data.schoolResults,
                                schoolName: res.data.schoolNames,
                                serialList: res.data.serialList,
                                chartAvg: res.data.comprehensivepointsavg,
                                searchChartLoading: false,
                                tableLoading: false,
                                alertVisible: false,
                                isSearch: true
                            });
                            if(values.average == 1){
                                let schoolResultAvg = [];
                                let schoolNameAvg = [];
                                let serialListAvg = [];
                                let t1 = [];
                                let t3 = [];
                                let count = 0;
                                for(let i = 0;i < this.state.schoolResult.length;i++){
                                    for(let j = 0;j < this.state.schoolResult[i].length;j++){
                                        if(parseFloat(this.state.schoolResult[i][j]) <= parseFloat(this.state.chartAvg)){
                                            if(count != 0 && count % 5 == 0){
                                                schoolResultAvg.push(t1);
                                                schoolNameAvg.push(t3);
                                                serialListAvg.push(parseInt((count-1) / 5) + 1);
                                                t1 = [];
                                                t3 = [];
                                            }
                                            t1.push(this.state.schoolResult[i][j]);
                                            t3.push(this.state.schoolName[i][j]);
                                            count++;
                                        }
                                    }
                                }
                                if(t1.length != 0){
                                    schoolResultAvg.push(t1);
                                    schoolNameAvg.push(t3);
                                    serialListAvg.push(parseInt((count-1) / 5) + 1);
                                }
                                this.setState({
                                    schoolResult: schoolResultAvg,
                                    schoolName: schoolNameAvg,
                                    serialList: serialListAvg,
                                })
                            }
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });



            }
        });
    }
    clearAll = () => {
        this.setState({
            filteredInfo: null,
            sortedInfo: null,
        });
    }
    handleChange = (pagination, filters, sorter) => {
        this.setState({
            filteredInfo: filters,
            sortedInfo: sorter,
        });
    }
    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
    }
    handleSearchReset = clearFilters => () => {
        clearFilters();
    }
    onRef = (ref) => {
        this.child = ref
    }

    searchReset = () => {
        this.props.form.resetFields();
    }

    setFullScreen(opts) {
        this.setState({
            fullScreenVisible: true,
        })
        let fullchart = echarts.init(document.getElementById('fullScreen'))
        fullchart.setOption(opts);
    }

    fullScreenCancel() {
        this.setState({
            fullScreenVisible: false,
        })
    }
    handleSelectTime = (value, dateString) => {
        if (dateString[0] != '' && dateString[1] != '') {
            this.setState({
                startTime: dateString[0],
                endTime: dateString[1],
            })
        }

    }

    handleChange2() {
        console.log("handleChange2()=========================")
    }

    getSchoolLevelByEduId(id, allType){
        getSchoolLevelByEduIdApi(id, allType)
            .then((res) => {
                this.setState({
                    schoolLevel: res.data,
                });

            })
    }

    

    render() {
        let schoolLevelOptions = [];
        schoolLevelOptions.push(<Option value={null} key={-1}>全部</Option>)
        if (this.state.schoolLevel.length != 0) {
            schoolLevelOptions.push(this.state.schoolLevel.map((d, index) =>
                <Option value={d.schoolLevel} key={index}>{d.schoolLevel}</Option>
            ))
        }
        let countyOptions = [];
        let name = sessionStorage.getItem("departmentName")
        let id = parseInt(sessionStorage.getItem("departmentId"))
        countyOptions.push(<Option value={-id} key={-id}>{name.substring(0, name.indexOf("市"))}全市</Option>)
        if(this.state.countyList.length != 0){
            countyOptions.push(this.state.countyList.map((item) =>
                <Option value={item.id} key={item.id}>{item.name}</Option>
            ))
        }
        const { getFieldDecorator, getFieldValue } = this.props.form;
        let { sortedInfo, filteredInfo } = this.state;
        sortedInfo = sortedInfo || {};
        filteredInfo = filteredInfo || {};
        const columnsSearch = [{
            title: "序号",
            dataIndex: "key",
            key: "key"
        }, {
            title: "学校",
            dataIndex: "schoolname",
            key: "schoolname",
            filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                <div className="custom-filter-dropdown">
                    <Input
                        ref={ele => this.searchInput = ele}
                        value={selectedKeys[0]}
                        onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                        onPressEnter={this.handleSearch(selectedKeys, confirm)}
                    />
                    <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                    <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                </div>
            ),
            filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
            onFilter: (value, record) => record.schoolname.toLowerCase().includes(value.toLowerCase()),
            onFilterDropdownVisibleChange: (visible) => {
                if (visible) {
                    setTimeout(() => {
                        this.searchInput.focus();
                    });
                }
            }
        }, 
        sessionStorage.getItem("departmentType") == "教育局" ? 
        {
            title: "区县",
            dataIndex: "departmentName",
            key: "departmentName"
        }:{}, {
            title: "巡检积分",
            dataIndex: "inspectpoints",
            key: "inspectpoints",
            sorter: (a, b) => a.inspectpoints - b.inspectpoints,
            sortDirections: ['descend', 'ascend'],
        },
        {
            title: "巡更积分",
            dataIndex: "patrolpoints",
            key: "patrolpoints",
            sorter: (a, b) => a.patrolpoints - b.patrolpoints,
            sortDirections: ['descend', 'ascend'],
        },
        {
            title: "隐患积分",
            dataIndex: "dangerdealpoints",
            key: "dangerdealpoints",
            sorter: (a, b) => a.dangerdealpoints - b.dangerdealpoints,
            sortDirections: ['descend', 'ascend'],
        },
        {
            title: "综合积分",
            dataIndex: "comprehensivepoints",
            key: "comprehensivepoints",
            sorter: (a, b) => a.comprehensivepoints - b.comprehensivepoints,
            sortDirections: ['descend', 'ascend'],

        },
        {
            title: '详情',
            dataIndex: 'action',
            key: 'action',
            render: (text, record) => {
                //  console.log("============================", record)
                return (
                    <span>
                        <a
                            onClick={toSchoolUrl.bind(this, record)}
                            // href={this.stahoolUrl}   
                            target="_blank"
                        >
                            查看详情
                        </a>
                        {/* <Button onClick={this.toSchoolUrl.bind(this, record)}> 查看详情</Button> */}
                    </span>
                )
            }
        }]
        let labelCol = {
            sm: { span: 6 },
            xl: { span: 6 },
            xxl: { span: 5 },
        };

        let wrapperCol = {
            sm: { span: 18 },
            xl: { span: 18 },
            xxl: { span: 19 },
        };

        // Excel头部标题
        const header = [
            {
                title: '序号',
                dataIndex: 'key',
                key: 'key',
            }, {
                title: '学校',
                dataIndex: 'schoolname',
                key: 'schoolname',
            }, {
                title: '区县',
                dataIndex: 'departmentName',
                key: 'departmentName',
            }, {
                title: '巡更积分(分)',
                dataIndex: 'patrolpoints',
                key: 'patrolpoints',
            }, {
                title: '巡更积分排名',
                dataIndex: 'patrolpointsRank',
                key: 'patrolpointsRank',
            }, {
                title: '巡检积分(分)',
                dataIndex: 'inspectpoints',
                key: 'inspectpoints',
            }, {
                title: '巡检积分排名',
                dataIndex: 'inspectpointsRank',
                key: 'inspectpointsRank',
            }, {
                title: '隐患积分(分)',
                dataIndex: 'dangerdealpoints',
                key: 'dangerdealpoints',
            }, {
                title: '隐患积分排名',
                dataIndex: 'dangerdealpointsRank',
                key: 'dangerdealpointsRank',
            }, {
                title: '综合积分(分)',
                dataIndex: 'comprehensivepoints',
                key: 'comprehensivepoints',
            }
        ]

        



        return (
            <div style={{ marginBottom: 16 }}>
                <Form style={{
                    padding: '12px',
                    backgroundColor: '#fafafa',
                    borderRadius: 8,
                    marginBottom: 16,
                }}
                    layout="inline"
                    onSubmit={this.searchSubmit}>
                    <Row>
                        <Col span={8}>
                            <FormItem
                                label="截止日期"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("deadline", {
                                    rules: [{
                                        type: 'array',
                                        required: false,
                                    }],
                                    initialValue: [ // 核心代码
                                        moment(this.getBeforeWeekTime(), dateFormat),
                                        moment(this.getBeforeDayTime(), dateFormat),
                                      ],
                                })(
                                    <RangePicker
                                        style={{ width: '100%' }}
                                        format="YYYY-MM-DD"
                                        onChange={this.handleSelectTime} />
                                )}
                            </FormItem>
                        </Col>
                        {sessionStorage.getItem("departmentType") == "教育局" ? (
                            <Col span={5}>
                            <FormItem
                                label="区县"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("county", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请选择区县"
                                        onSelect = {(e) => {
                                            if(e < 0){
                                                this.getSchoolLevelByEduId(parseInt(sessionStorage.getItem("departmentId")), 1)
                                            }else {
                                                this.getSchoolLevelByEduId(e, 0)
                                            }
                                        }}>
                                        {countyOptions}
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        )
                        :null
                        }
                        <Col span={8}>
                            <FormItem
                                label="学校类型"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("schoolLevel", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请选择学校类型">
                                        {schoolLevelOptions}
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8}>
                        <FormItem
                                label="数值"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("average", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请选择数值情况">
                                        <Option value={0} key={0}>所有</Option>
                                        <Option value={1} key={1}>低于平均值</Option>
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        <Col>
                            <FormItem
                                style={{ float: 'right' }}>
                                <Button type="primary" style={{ marginLeft: 8 }} htmlType="submit">搜索</Button>
                                <Button style={{ marginLeft: 8 }} onClick={this.searchReset}>清空</Button>
                                <Button type="primary" style={{ marginLeft: 8 }} onClick={() =>  {
                                    exportExcel(header, this.state.columnData, "学校综合积分排名.xlsx")
                                    }}>导出Excel
                                </Button>   
                            </FormItem>
                        </Col>
                    </Row>
                </Form>
                <div>
                    {
                        this.state.isSearch ?
                            (
                                <div style={{
                                    marginBottom: 16,
                                    padding: 16,
                                    width: '100%',
                                    height: 350,
                                    border: '1px solid',
                                    borderColor: '#f5f5f5'
                                }}>
                                    <Skeleton loading={this.state.searchChartLoading} active>
                                        <ChartSearchComprehensivePoints
                                            that={this}
                                            schoolName={this.state.schoolName}
                                            schoolResult={this.state.schoolResult}
                                            serialList={this.state.serialList}
                                            chartAvg={this.state.chartAvg}
                                            divId={'chartSearch'} />
                                    </Skeleton>
                                </div>
                            ) : null
                    }
                    {
                        this.state.isSearch ? 
                        (
                            <Alert
                            message="学校综合积分说明"
                            description={"学校综合积分=在统计时间范围内，该学校的巡检积分+巡更积分+隐患积分"}
                            type="info"
                            showIcon/>
                        ) : null
                    }
                    <Table
                        dataSource={this.state.columnData}
                        columns={columnsSearch}
                        loading={this.state.tableLoading}
                        locale={{ emptyText: '暂无数据' }}
                        onChange={this.handleChange2}
                        rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                        pagination={{  //分页
                            total: this.state.searchData.length, //数据总数量
                            defaultPageSize: 10, //默认显示几条一页
                            //pageSize: 10,
                            showTotal: function (total) {  //设置显示一共几条数据
                                return '共 ' + total + ' 条数据';
                            },
                            showSizeChanger: true,
                            showQuickJumper: true,
                            pageSizeOptions: [5, 10, 20, 30]
                        }} />
                </div>
            </div>
        );
    }
}

const ComprehensivePointsRank = Form.create()(comprehensivePointsRank);

//综合积分排名排名柱状图
class ChartSearchComprehensivePoints extends Component {
    constructor(props) {
        super(props);
        this.state = {
            schoolResult: props.schoolResult || [],
            schoolName: props.schoolName || [],
            serialList: props.serialList || [],
            that: props.that,
            currentIndex: 0,
            divId: props.divId,
            data1: 0,
            schoolNamePart: [],
            chartAvg: props.chartAvg
        };
    }

    componentWillReceiveProps(props) {

        if (JSON.stringify(props.schoolName) != JSON.stringify(this.state.schoolName) && props.serialList.length > 0) {
            this.setState({
                that: props.that,
                schoolResult: props.schoolResult,
                schoolName: props.schoolName,
                serialList: props.serialList,
                chartAvg: props.chartAvg
            }, () => {
                this.drawChart()
            })
        }
    }

    componentDidMount() {
        let optionData = [];
        if (this.state.schoolName.length != 0) {
            this.drawChart();
        }
    }


    drawChart() {

        let optionData = [];

        let chart = echarts.init(document.getElementById('chartSearch'));
        let option = {

            baseOption: {
                timeline: {
                    axisType: 'category',
                    triggerEvent: true,
                    playInterval: 1000,
                    data: this.state.serialList
                },
                title: {
                    text: '学校综合积分排名',
                    left: 'center',
                    top: '10px',
                    subtext:'平均值: ' + this.state.chartAvg +'分',
                    subtextStyle: {
                        fontSize: 16
                    }
                },
                color: ['#3398DB'],
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                        type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                    }
                },
                toolbox: {
                    show: true,
                    feature: {
                        dataZoom: {
                            yAxisIndex: 'none'
                        },
                        dataView: { readOnly: false },
                        magicType: { type: ['line', 'bar'] },
                        restore: {},
                        saveAsImage: {}
                    }
                },
                grid: {
                    left: '5%',
                    right: '5%',
                    bottom: '50px',
                    top: '90px',
                    containLabel: true
                },
                xAxis: [
                    {
                        type: 'category',
                        data: this.state.schoolNamePart,
                        axisTick: {
                            alignWithLabel: true
                        },
                        axisLabel: {
                            textStyle: {
                                fontSize: 16
                            }
                        }
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        axisLabel: {
                            formatter: '{value}分',
                            textStyle: {
                                fontSize: 16
                            }
                        }
                    }
                ],

                series: [
                    { name: '综合积分', type: 'bar' },
                ],

            },
            options:[]
        };

        
        for (var i = 0; i < this.state.schoolResult.length; i++) {
            let schoolNameList = [];
            for(var j = 0;j < this.state.schoolName[i].length; j++){
                let arr = this.state.schoolName[i][j].split("\n");
                schoolNameList.push(arr[0]);
            }
            
            option.options.push({
                xAxis: {
                    data: sessionStorage.getItem("departmentType") == "教育局" ? this.state.schoolName[i]
                    : schoolNameList
                },
                series: [                
                    {
                        name: '综合积分',
                        type: 'bar',
                        data: this.state.schoolResult[i],
                        barGap: '100%',
                        barMaxWidth: 25,
                        animation: false,
                        itemStyle:
                            {
                                color: 'rgb(255, 70, 131)',
                                normal: {
                                    label: {
                                        show: true, //开启显示
                                        position: 'top', //在上方显示
                                        textStyle: { //数值样式
                                            color: 'black',
                                            fontSize: 14
                                        }
                                    }
                                }
                            },
                        showBackground: true,
                        backgroundStyle: {
                            color: 'rgba(180, 180, 180, 0.2)'
                        },
                        markPoint: {
                            data: [
                                {
                                    type: 'max', name: '最大值'
                                }, {
                                    type: 'min', name: '最小值'
                                }
                            ]
                        }
                    }
                ]
            })
        }
        chart.setOption(option);
    }


    render() {
        let chartStyle = {
            height: '100%',
            width: '100%',
        };
        return (<div id={this.state.divId} style={chartStyle} />)
    }
}

class xunchaRecord extends Component {
    constructor(props) {
        super(props);
        this.state = {
            //detailVisible: false,
            alertVisible: false, //提示
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            tableLoading: true,
            data: [],
            filteredInfo: null,
            sortedInfo: null,
            isSearch: false,
            classNameArr: [],
            existCategory: [],
            searchData: [],
            filteredInfo2: null,
            sortedInfo2: null,
            // searchText2: '',
            detailVisible: false,
            detailExist: false,
            countyList:[],
            searchChartLoading: true,
            chartInspectSearchData: {}
        };

    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        let departmentId
        if(sessionStorage.getItem("departmentType") == "教育局"){
            departmentId = -parseInt(sessionStorage.getItem("departmentId"))
        }else{
            departmentId = parseInt(sessionStorage.getItem("departmentId"))
        }
        this.setState({
            tableLoading: true
        });
        let searchData = []
        XunchaRecordSearchApi(departmentId, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined)
        .then(res => {
            res.data.forEach((item, index) => {
                searchData.push({
                    key: index + 1,
                    theme: item.theme,
                    realname: item.realname,
                    schoolname: item.schoolname,
                    type: item.type,
                    createTime: item.createTime,
                    modifyTime: item.modifyTime,
                    status: item.status,
                    normal: item.normal,
                    superviseId: item.superviseId,
                    id: item.id
                });
            });
            this.setState({
                isSearch: true,
                searchData: searchData,
                tableLoading: false,
                alertVisible: false,
            });
        })
        .catch((e) => {
            if (e.response) {
                //请求已发出，服务器返回状态码不是2xx。
                console.info(e.response.data)
                console.info(e.response.status)
                console.info(e.response.headers)
            } else if (e.request) {
                // 请求已发出，但没有收到响应
                // e.request 在浏览器里是一个XMLHttpRequest实例，
                // 在node中是一个http.ClientRequest实例
                console.info(e.request)
            } else {
                //发送请求时异常，捕捉到错误
                console.info('error', e.message)
            }
            console.info(e.config)
        });

        getDepartmentApi(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                this.setState({
                    countyList: res.data
                });
            }).catch((e) => {
                console.log(e);
            })
        
    }


    searchSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            console.log('Received values of form: ', values);
            if (values.realname == undefined && values.theme == undefined && values.deadline == undefined && values.type == undefined && values.status == undefined && values.normal == undefined && values.schoolname == undefined && values.departmentId == undefined) {
                message.error('请至少填写一项条件再进行搜索');
            } else {
                this.setState({
                    tableLoading: true
                });
                let startTime = null;
                let endTime = null;
                if(values.deadline != undefined){
                    startTime = moment(values.deadline[0]).format('YYYY-MM-DD');
                    endTime = moment(values.deadline[1]).format('YYYY-MM-DD');
                }
                let searchData = [];
                let departmentId;
                if(sessionStorage.getItem("departmentType") == "教育局"){
                    departmentId = values.departmentId
                }else{
                    departmentId = parseInt(sessionStorage.getItem("departmentId"))
                }
                XunchaRecordSearchApi(departmentId, values.realname, values.schoolname, values.type, values.status, startTime, endTime, values.theme, values.normal)
                    .then(res => {
                        res.data.forEach((item, index) => {
                            searchData.push({
                                key: index + 1,
                                theme: item.theme,
                                realname: item.realname,
                                schoolname: item.schoolname,
                                type: item.type,
                                createTime: item.createTime,
                                modifyTime: item.modifyTime,
                                status: item.status,
                                normal: item.normal,
                                superviseId: item.superviseId,
                                id: item.id
                            });
                        });
                        this.setState({
                            isSearch: true,
                            searchData: searchData,
                            tableLoading: false,
                            alertVisible: false,
                        });
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });


            }
        });
    }

    showDetailDrawer(superviseId, id) {

        this.setState({
            detailVisible:true,
            detailExist:true,
            currentSuperviseId:superviseId,
            currentId:id
        })
    }

    handleDetailDrawerCancel() {
        this.setState({
            detailVisible: false,
        })
    }

    //关闭 alert 的提示
    handleClose() {
        this.setState({ alertVisible: false });
    }

    clearAll = () => {
        this.setState({
            filteredInfo: null,
            sortedInfo: null,
        });

    }

    handleChange = (pagination, filters, sorter) => {
        //console.log('Various parameters', pagination, filters, sorter);
        this.setState({
            filteredInfo: filters,
            sortedInfo: sorter,
        });
    }

    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
        // this.setState({
        //     searchText: selectedKeys[0],
        // });
    }

    handleSearchReset = clearFilters => () => {
        clearFilters();
        // this.setState({
        //     searchText: '',
        // });
    }

    clearAll2 = () => {
        this.setState({
            filteredInfo2: null,
            sortedInfo2: null,
        });

    }

    handleChange2 = (pagination, filters, sorter) => {
        //console.log('Various parameters', pagination, filters, sorter);
        this.setState({
            filteredInfo2: filters,
            sortedInfo2: sorter,
        });
    }

    handleSearch2 = (selectedKeys, confirm) => () => {
        confirm();
        // this.setState({
        //     // searchText2: selectedKeys[0],
        // });
    }

    handleSearchReset2 = clearFilters => () => {
        clearFilters();
        // this.setState({
        //     // searchText2: '',
        // });
    }

    onRef = (ref) => {
        this.child = ref
    }

    searchReset = () => {
        this.props.form.resetFields();
        this.setState({
            isSearch: false,
        })
    }

    fullScreenCancel() {
        this.setState({
            fullScreenVisible: false,
        })
    }


    render() {
        let countyOptions = [];
        let name = sessionStorage.getItem("departmentName")
        let id = parseInt(sessionStorage.getItem("departmentId"))
        countyOptions.push(<Option value={-id} key={-id}>{name.substring(0, name.indexOf("市"))}全市</Option>)
        if(this.state.countyList.length != 0){
            countyOptions.push(this.state.countyList.map((item) =>
                <Option value={item.id} key={item.id}>{item.name}</Option>
            ))
        }
        let { sortedInfo, filteredInfo } = this.state;
        sortedInfo = sortedInfo || {};
        filteredInfo = filteredInfo || {};
        const columns = [{
            title: "序号",
            dataIndex: "key",
            key: "key"
        },
        {
            title: "巡查主题",
            dataIndex: "theme",
            key: "theme",
        },
        {
            title: "巡查人员",
            dataIndex: "realname",
            key: "realname",
        },
        {
            title: "巡查学校",
            dataIndex: "schoolname",
            key: "schoolname",
        },
        {
            title: "巡查类型",
            dataIndex: "type",
            key: "type",
        },
        {
            title: "开始时间",
            dataIndex: "createTime",
            key: "createTime",
        },
        {
            title: "结束时间",
            dataIndex: "modifyTime",
            key: "modifyTime",
        },
        {
            title: "巡查状态",
            dataIndex: "status",
            key: "status",
        },
        {
            title: "异常情况",
            dataIndex: "normal",
            key: "normal",
        },
        ];

        const { getFieldDecorator, getFieldValue } = this.props.form;
        let { sortedInfo2, filteredInfo2 } = this.state;
        sortedInfo2 = sortedInfo2 || {};
        filteredInfo2 = filteredInfo2 || {};


        let keyWidth = undefined;
        let themeWidth = undefined;
        let realnameWidth = undefined;
        let schoolnameWidth = undefined;
        let typeWidth = undefined;
        let statusWidth = undefined;
        let createTimeWidth = undefined;
        let modifyTimeWidth = undefined;
        let normalWidth = undefined;
        let actionWidth = undefined;

        let winWidth;
        // 获取窗口宽度
        if (window.innerWidth)
            winWidth = window.innerWidth;
        else if ((document.body) && (document.body.clientWidth))
            winWidth = document.body.clientWidth;
        if (winWidth < 1500) {
            keyWidth = 60;
            themeWidth = 120;
            realnameWidth = 90;
            schoolnameWidth = 120;
            typeWidth = 90;
            statusWidth = 90;
            createTimeWidth = 150;
            modifyTimeWidth = 150;
            normalWidth = 90;
            actionWidth = 90;
        }

            const columnsSearch = [{
                title: "序号",
                dataIndex: "key",
                key: "key",
                width: keyWidth,
            }, {
                title: "巡查主题",
                dataIndex: "theme",
                key: "theme",
                width: themeWidth,
                filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                    <div className="custom-filter-dropdown">
                        <Input
                            ref={ele => this.searchInput = ele}
                            value={selectedKeys[0]}
                            onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                            onPressEnter={this.handleSearch(selectedKeys, confirm)}
                        />
                        <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                        <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                    </div>
                ),
                filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
                onFilter: (value, record) => record.theme.toLowerCase().includes(value.toLowerCase()),
                onFilterDropdownVisibleChange: (visible) => {
                    if (visible) {
                        setTimeout(() => {
                            this.searchInput.focus();
                        });
                    }
                }
            }, {
                title: "巡查人员",
                dataIndex: "realname",
                key: "realname",
                width: realnameWidth,
                filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                    <div className="custom-filter-dropdown">
                        <Input
                            ref={ele => this.searchInput = ele}
                            value={selectedKeys[0]}
                            onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                            onPressEnter={this.handleSearch(selectedKeys, confirm)}
                        />
                        <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                        <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                    </div>
                ),
                filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
                onFilter: (value, record) => record.realname.toLowerCase().includes(value.toLowerCase()),
                onFilterDropdownVisibleChange: (visible) => {
                    if (visible) {
                        setTimeout(() => {
                            this.searchInput.focus();
                        });
                    }
                }
            }, {
                title: "巡查学校",
                dataIndex: "schoolname",
                key: "schoolname",
                width: schoolnameWidth,
                filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                    <div className="custom-filter-dropdown">
                        <Input
                            ref={ele => this.searchInput = ele}
                            value={selectedKeys[0]}
                            onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                            onPressEnter={this.handleSearch(selectedKeys, confirm)}
                        />
                        <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                        <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                    </div>
                ),
                filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
                onFilter: (value, record) => record.schoolname.toLowerCase().includes(value.toLowerCase()),
                onFilterDropdownVisibleChange: (visible) => {
                    if (visible) {
                        setTimeout(() => {
                            this.searchInput.focus();
                        });
                    }
                }
            }, {
                title: "巡查类型",
                dataIndex: "type",
                key: "type",
                width: typeWidth,
                render: (text) => {
                    if (text == '1') { return (<span>专项巡查</span>) }
                    else if (text == '2') { return (<span>定期巡查</span>) }
                }
            }, {
                title: '开始时间',
                dataIndex: 'createTime',
                key: 'createTime',
                width: createTimeWidth,
                sorter: (a, b) => new Date(a.createTime).getTime() - new Date(b.createTime).getTime(),
                sortOrder: sortedInfo2.columnKey === 'createTime' && sortedInfo2.order,
            }, {
                title: '结束时间',
                dataIndex: 'modifyTime',
                key: 'modifyTime',
                width: modifyTimeWidth,
                sorter: (a, b) => new Date(a.modifyTime).getTime() - new Date(b.modifyTime).getTime(),
                sortOrder: sortedInfo2.columnKey === 'modifyTime' && sortedInfo2.order,
            }, {
                title: "巡查状态",
                dataIndex: "status",
                key: "status",
                width: statusWidth,
                render: (text) => {
                    if (text == '1') { return (<span style={{ color: 'green' }}>进行中</span>) }
                    else if (text == '2') { return (<span style={{ color: 'red' }}>已结束</span>) }
                }
            }, {
                title: "异常情况",
                dataIndex: "normal",
                key: "normal",
                width: normalWidth,
                render: (text) => {
                    if (text != '2') { return (<span style={{ color: 'green' }}>无异常</span>) }
                    else if (text == '2') { return (<span style={{ color: 'red' }}>有异常</span>) }
                },
            }, {
                title: "操作详情",
                key: "action",
                width: actionWidth,
                render: (text, record) => {
                        return (
                            <span>
                                <a
                                    href="javascript:;"
                                    onClick={this.showDetailDrawer.bind(this, record.superviseId, record.id)}>
                                    查看详情
                                </a>
                            </span>
                        )
                }
            }
        ];



        let labelCol = {
            sm: { span: 6 },
            xl: { span: 6 },
            xxl: { span: 5 },
        };

        let wrapperCol = {
            sm: { span: 18 },
            xl: { span: 18 },
            xxl: { span: 19 },
        };

        return (
            <div style={{ marginBottom: 16 }}>
                <Form
                    style={{
                        padding: '12px',
                        backgroundColor: '#fafafa',
                        borderRadius: 8,
                        marginBottom: 16,
                    }}
                    layout="inline"
                    onSubmit={this.searchSubmit}>
                    <Row>
                        <Col span={8}>
                            <FormItem
                                label="巡查主题"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("theme", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Input
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请输入巡查主题"
                                    ></Input>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8}>
                            <FormItem
                                label="巡查学校"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("schoolname", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Input
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请输入巡查学校"
                                    ></Input>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8}>
                            <FormItem
                                    label="巡查类型"
                                    style={{ width: '100%' }}
                                    labelCol={labelCol}
                                    wrapperCol={wrapperCol}>
                                    {getFieldDecorator("type", {
                                        rules: [{
                                            required: false,
                                        }]
                                    })(
                                        <Select
                                            allowClear={true}
                                            style={{ width: '100%' }}
                                            placeholder="请选择巡查类型">
                                            <Option value={1}>专项巡查</Option>
                                            <Option value={2}>定期巡查</Option>
                                        </Select>
                                    )}
                                </FormItem>
                            </Col>
                    </Row>
                    <Row>
                        <Col span={8}>
                            <FormItem
                                label="截止日期"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("deadline", {
                                    rules: [{
                                        type: 'array',
                                        required: false,
                                    }]
                                })(
                                    <RangePicker
                                        style={{ width: '100%' }}
                                        format="YYYY-MM-DD" />
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8}>
                            <FormItem
                                    label="巡查状态"
                                    style={{ width: '100%' }}
                                    labelCol={labelCol}
                                    wrapperCol={wrapperCol}>
                                    {getFieldDecorator("status", {
                                        rules: [{
                                            required: false,
                                        }]
                                    })(
                                        <Select
                                            allowClear={true}
                                            style={{ width: '100%' }}
                                            placeholder="请选择巡查状态">
                                            <Option value={1}>进行中</Option>
                                            <Option value={2}>已结束</Option>
                                        </Select>
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={8}>
                            <FormItem
                                label="异常情况"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("normal", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请选择异常情况">
                                        <Option value={1}>无异常</Option>
                                        <Option value={2}>有异常</Option>
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={8}>
                            <FormItem
                                label="巡查人员"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("realname", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Input
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请输入巡查人员"
                                    ></Input>
                                )}
                            </FormItem>
                        </Col>
                        {sessionStorage.getItem("departmentType") == "教育局" ? (
                            <Col span={8}>
                            <FormItem
                                label="区县"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("departmentId", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请选择区县"
                                        onSelect = {(e) => {
                                            if(e < 0){
                                                this.getSchoolLevelByEduId(parseInt(sessionStorage.getItem("departmentId")), 1)
                                            }else {
                                                this.getSchoolLevelByEduId(e, 0)
                                            }
                                        }}>
                                        {countyOptions}
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        )
                        :null
                        }
                        <FormItem
                            style={{ float: 'right' }}>
                            <Button type="primary" htmlType="submit">搜索</Button>
                            <Button style={{ marginLeft: 8 }} onClick={this.searchReset}>清空</Button>
                        </FormItem>
                    </Row>
                </Form>
                    <div>
                        <Table
                            dataSource={this.state.searchData}
                            columns={columnsSearch}
                            loading={this.state.tableLoading}
                            locale={{ emptyText: '暂无数据' }}
                            onChange={this.handleChange2}
                            rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                            pagination={{  //分页
                                total: this.state.searchData.length, //数据总数量
                                defaultPageSize: 10, //默认显示几条一页
                                //pageSize: 10,
                                showTotal: function (total) {  //设置显示一共几条数据
                                    return '共 ' + total + ' 条数据';
                                },
                                showSizeChanger: true,
                                showQuickJumper: true,
                                pageSizeOptions: [5, 10, 20, 30]
                            }} />
                        {
                            this.state.detailExist ? (
                                <XunchaConditionDetail
                                    visible={this.state.detailVisible}
                                    currentSuperviseId={this.state.currentSuperviseId}
                                    currentId={this.state.currentId}
                                    that={this} />
                            ) : null
                        }
                    </div>
            </div>
        )
    }
}
const XunchaRecord = Form.create()(xunchaRecord);

class XunchaConditionDetail extends Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: props.visible,
            currentSuperviseId: props.currentSuperviseId,
            currentId: props.currentId,
            that: props.that,
            confirmLoading: false,
            previewVisible: false,
            previewImage: '',
            detailData: [],
            dealDetailData: [],
        };
    }

    componentDidMount() {
        this.refreshData(this.props.currentSuperviseId, this.props.currentId);
        // console.log(this.state.detailData)
    }

    componentWillReceiveProps(props) {
        this.setState({
            visible:props.visible,
            currentSuperviseId: props.currentSuperviseId,
            currentId: props.currentId,
            that: props.that,
        })
        if (props.visible) {
            this.refreshData(props.currentSuperviseId, props.currentId);
            // console.log(this.state.detailData)
        }
    }

    refreshData(currentSuperviseId, currentId){
        this.setState({
            confirmLoading: true,
        })
        let detailData = []
        getXunchaConditionDetail(currentSuperviseId, currentId)
            .then((res) => {
                res.data.forEach((item, index) => {
                    detailData.push({
                        key: index + 1,
                        content: item.content,
                        normal: item.normal,
                        address: item.address,
                        safecontent: item.safecontent,
                        video: item.video,
                        photo: item.photo,
                        realname: item.realname,
                        status: item.status,
                        createTime: item.createTime
                    });
                });
                this.setState({
                    detailData: detailData,
                    confirmLoading: false,
                })
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

        let dealDetailData = []
        getXunchaDealDetail(currentSuperviseId, currentId)
            .then((res) => {
                res.data.forEach((item, index) => {
                    dealDetailData.push({
                        key: index + 1,
                        content: item.content,
                        dealContent: item.dealContent,
                        dealPhoto: item.dealPhoto,
                        dealVideo: item.dealVideo,
                        realname: item.realname,
                        createTime: item.createTime
                    });
                });
                this.setState({
                    dealDetailData: dealDetailData,
                    confirmLoading: false,
                })
                console.log(this.state.dealDetailData)
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    handlePreview = (src) => {
        this.setState({
            previewImage: src,
            previewVisible: true,
        });
    }

    handlePreviewCancel = () => this.setState({ previewVisible: false })
       
    render() {


        const Panel = Collapse.Panel;
        const gridStyle = {
            width: '33.33333333333333333333333%',
            height: '150px',
            textAlign: 'center',
            position: 'relative'
        };
        
        const prepanels = this.state.detailData.map((d, index) => {
            let status;
            if (d.normal == 0) {
                status = 0;
            } else if (d.normal == 1) {
                status = 1;
            } else if (d.normal == 2) {
                status = 2;
            }

            let header = (
                <div style={{ height: '100%', width: '100%' }}>
                    <div style={{ width: '80%', left: 0 }}>
                        {d.content}
                    </div>
                    <img
                        style={{
                            width: '15%',
                            right: 5,
                            top: 0,
                            bottom: 0,
                            margin: 'auto',
                            position: 'absolute',
                        }}
                        alt="计划状态"
                        src={require('../img/xuncha' + status + '.png')}
                    />
                </div>
            );

            let prePhotos;
            let preVideo;
            if (d.photo == ''|| d.photo == undefined) {
                prePhotos = (
                    <Card.Grid
                        key={0}
                        style={gridStyle}>
                        <img
                            style={{
                                width: 'auto',
                                height: 'auto',
                                position: 'absolute',
                                top: 0,
                                left: 0,
                                right: 0,
                                bottom: 0,
                                margin: 'auto',
                                maxWidth: '100%',
                                maxHeight: '100%',
                                padding: 5,
                            }}
                            alt="暂无图片"
                            src={require('../img/nophoto.png')} />
                    </Card.Grid>
                );
            } else {
                let photoArr = d.photo.split(',')
                prePhotos = (
                    photoArr.map((p, i) => {
                        return(
                            <Card.Grid
                                key={i}
                                style={gridStyle}>
                                <img
                                    style={{
                                        width: 'auto',
                                        height: 'auto',
                                        position: 'absolute',
                                        top: 0,
                                        left: 0,
                                        right: 0,
                                        bottom: 0,
                                        margin: 'auto',
                                        maxWidth: '100%',
                                        maxHeight: '100%',
                                        padding: 5,
                                    }}
                                    alt='异常照片'
                                    src={UrlPrefix + p}
                                    // onClick={this.handlePreview.bind(this, UrlPrefix + p)} 
                                    />
                            </Card.Grid>
                        )
                    })
                    
                );
            }
            preVideo = (
                <Card.Grid
                    key={0}
                    style={gridStyle}>
                    <video
                        style={{
                            width: 'auto',
                            height: 'auto',
                            position: 'absolute',
                            top: 0,
                            left: 0,
                            right: 0,
                            bottom: 0,
                            margin: 'auto',
                            maxWidth: '100%',
                            maxHeight: '100%',
                            padding: 5,
                        }}
                        src={UrlPrefix + d.video} controls />
                </Card.Grid>
            );

            let preData = [{
                title: '上报学校',
                description: d.address,
            }, {
                title: '上报人',
                description: d.realname,
            }, {
                title: '状态',
                description: d.status,
            }, {
                title: '上报时间',
                description: d.createTime
            }, {
                title: '上报内容',
                description: d.safecontent,
            }, {
                title: '上报照片',
                description: (
                    <Card
                        hoverable
                        style={{ marginTop: '10px' }}>
                            <RViewerJS>
                        {prePhotos}
                        </RViewerJS>
                    </Card>),
            }, {
                title: '上报视频',
                description: (
                    (d.video == ""|| d.video == undefined) ?
                        <span>暂无视频</span>
                        :
                        <Card
                            hoverable
                            style={{ marginTop: '10px' }}>
                                <RViewerJS>
                            {preVideo}
                            </RViewerJS>
                        </Card>
                ),
            }];
            
            return (
                <Panel header={header} key={index + ''} disabled={(status == 2) ? false : true} >
                    <List
                            itemLayout="horizontal"
                            dataSource={preData}
                            renderItem={item => (
                                <List.Item>
                                    <List.Item.Meta
                                        title={item.title}
                                        description={item.description}
                                    />
                                </List.Item>
                            )}
                        />
                </Panel>
            );
        })
        let dealpanels
        if (this.state.dealDetailData.length !=0 ) {
            dealpanels = this.state.dealDetailData.map((d, index) => {
                let header = (
                    <div style={{ height: '100%', width: '100%' }}>
                        <div style={{ width: '80%', left: 0 }}>
                            {d.content}
                        </div>
                        <img
                            style={{
                                width: '15%',
                                right: 5,
                                top: 0,
                                bottom: 0,
                                margin: 'auto',
                                position: 'absolute',
                            }}
                            alt="计划状态"
                            src={require('../img/xuncha2.png')}
                        />
                    </div>
                );

                let dealPhotos;
                let dealVideo;
                if (d.dealPhoto == ''|| d.dealPhoto == undefined) {
                    dealPhotos = (
                        <Card.Grid
                            key={0}
                            style={gridStyle}>
                            <img
                                style={{
                                    width: 'auto',
                                    height: 'auto',
                                    position: 'absolute',
                                    top: 0,
                                    left: 0,
                                    right: 0,
                                    bottom: 0,
                                    margin: 'auto',
                                    maxWidth: '100%',
                                    maxHeight: '100%',
                                    padding: 5,
                                }}
                                alt="暂无图片"
                                src={require('../img/nophoto.png')} />
                        </Card.Grid>
                    );
                } else {
                    let photoArr = d.dealPhoto.split(',')
                    dealPhotos = (
                        photoArr.map((p, i) => {
                            return(
                                <Card.Grid
                                    key={i}
                                    style={gridStyle}>
                                    <img
                                        style={{
                                            width: 'auto',
                                            height: 'auto',
                                            position: 'absolute',
                                            top: 0,
                                            left: 0,
                                            right: 0,
                                            bottom: 0,
                                            margin: 'auto',
                                            maxWidth: '100%',
                                            maxHeight: '100%',
                                            padding: 5,
                                        }}
                                        alt='异常照片'
                                        src={UrlPrefix + p}
                                        onClick={this.handlePreview.bind(this, UrlPrefix + p)} />
                                </Card.Grid>
                            )
                        })
                        
                    );
                }
                dealVideo = (
                    <Card.Grid
                        key={0}
                        style={gridStyle}>
                        <video
                            style={{
                                width: 'auto',
                                height: 'auto',
                                position: 'absolute',
                                top: 0,
                                left: 0,
                                right: 0,
                                bottom: 0,
                                margin: 'auto',
                                maxWidth: '100%',
                                maxHeight: '100%',
                                padding: 5,
                            }}
                            src={UrlPrefix + d.dealVideo} controls />
                    </Card.Grid>
                );

                let dealData = [{
                    title: '处理人',
                    description: d.realname,
                }, {
                    title: '处理时间',
                    description: d.createTime
                }, {
                    title: '处理内容',
                    description: d.dealContent,
                }, {
                    title: '处理照片',
                    description: (
                        <Card
                            hoverable
                            style={{ marginTop: '10px' }}>
                                <RViewerJS>
                                {dealPhotos}
                                </RViewerJS>
                     
                        </Card>),
                }, {
                    title: '处理视频',
                    description: (
                        (d.dealVideo == ""|| d.dealVideo == undefined) ?
                            <span>暂无视频</span>
                            :
                            <Card
                                hoverable
                                style={{ marginTop: '10px' }}>
                                    <RViewerJS>
                                {dealVideo}
                                </RViewerJS>
                            </Card>
                    ),
                }];
                
                return (
                    <Panel header={header} key={index + ''}>
                        <List
                                itemLayout="horizontal"
                                dataSource={dealData}
                                renderItem={item => (
                                    <List.Item>
                                        <List.Item.Meta
                                            title={item.title}
                                            description={item.description}
                                        />
                                    </List.Item>
                                )}
                            />
                    </Panel>
                );
            })
        }else{
            dealpanels = <Panel header='此条暂无处理信息'></Panel>
        }

        return (
            <div>
                <Drawer
                    bodyStyle={{ paddingBottom: 80 }}
                    width={800}
                    title='巡查内容详情'
                    visible={this.state.visible}
                    onClose={this.state.that.handleDetailDrawerCancel.bind(this.state.that)}
                    destroyOnClose={true}
                    closable
                >
                    <Tabs
                        defaultActiveKey="1">
                        <TabPane tab={<span ><IconFont type="icon-weiwancheng" className='iconTabs' />上报信息</span>} key="1">
                            <Collapse>
                                {prepanels}
                            </Collapse>
                        </TabPane>
                        <TabPane tab={<span ><IconFont type="icon-yiwanchengdingdan" className='iconTabs' />处理信息</span>} key="2">
                            <Collapse>
                                {dealpanels}
                            </Collapse>
                        </TabPane>
                    </Tabs>
                    <div
                        style={{
                            position: 'absolute',
                            left: 0,
                            bottom: 0,
                            width: '100%',
                            borderTop: '1px solid #e9e9e9',
                            padding: '10px 16px',
                            background: '#fff',
                            textAlign: 'right',
                        }}
                    >
                        <Button size="large" onClick={this.state.that.handleDetailDrawerCancel.bind(this.state.that)}
                            style={{ marginRight: 20 }}>关闭</Button>
                    </div>
                </Drawer>
                <Modal
                    destroyOnClose
                    visible={this.state.previewVisible}
                    footer={null}
                    bodyStyle={{
                        paddingTop: 48,
                    }}
                    onCancel={this.handlePreviewCancel}>
                    <img
                        alt="照片"
                        style={{ width: '100%' }}
                        src={this.state.previewImage} />
                </Modal>
            </div>

        );
    }
}

class dailyRecord extends Component {
    constructor(props) {
        super(props);
        this.state = {
            //detailVisible: false,
            alertVisible: false, //提示
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            tableLoading: true,
            data: [],
            filteredInfo: null,
            sortedInfo: null,
            // searchText: '',
            // allCategory: [],
            // allStatus: []
            isSearch: false,
            classNameArr: [],
            existCategory: [],
            searchData: [],
            filteredInfo2: null,
            sortedInfo2: null,
            // searchText2: '',

            detailVisible: false,
            detailExist: false,

            searchChartLoading: true,
            chartInspectSearchData: {}
        };

    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        const departmentId = parseInt(sessionStorage.getItem("departmentId"))
        this.setState({
            tableLoading: true
        });
        let searchData = []
        DailyRecordSearchApi(departmentId, undefined, undefined, undefined, undefined, undefined, undefined)
        .then(res => {
            res.data.forEach((item, index) => {
                searchData.push({
                    key: index + 1,
                    id: item.id,
                    realname: item.realname,
                    schoolname: item.schoolname,
                    createTime: item.createTime,
                    modifyTime: item.modifyTime,
                    status: item.status,
                    normal: item.normal
                });
            });
            this.setState({
                isSearch: true,
                searchData: searchData,
                tableLoading: false,
                alertVisible: false,
            });
        })
        .catch((e) => {
            if (e.response) {
                //请求已发出，服务器返回状态码不是2xx。
                console.info(e.response.data)
                console.info(e.response.status)
                console.info(e.response.headers)
            } else if (e.request) {
                // 请求已发出，但没有收到响应
                // e.request 在浏览器里是一个XMLHttpRequest实例，
                // 在node中是一个http.ClientRequest实例
                console.info(e.request)
            } else {
                //发送请求时异常，捕捉到错误
                console.info('error', e.message)
            }
            console.info(e.config)
        });
    }


    searchSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            console.log('Received values of form: ', values);
            if (values.realname == undefined && values.schoolname == undefined && values.deadline == undefined && values.status == undefined && values.normal == undefined) {
                message.error('请至少填写一项条件再进行搜索');
            } else {
                this.setState({
                    tableLoading: true
                });
                let startTime = null;
                let endTime = null;
                if(values.deadline != undefined){
                    startTime = moment(values.deadline[0]).format('YYYY-MM-DD');
                    endTime = moment(values.deadline[1]).format('YYYY-MM-DD');
                }
                let searchData = [];
                const departmentId = parseInt(sessionStorage.getItem("departmentId"))
                DailyRecordSearchApi(departmentId, values.realname, values.schoolname, values.status, startTime, endTime, values.normal)
                    .then(res => {
                        res.data.forEach((item, index) => {
                            searchData.push({
                                key: index + 1,
                                id: item.id,
                                realname: item.realname,
                                schoolname: item.schoolname,
                                createTime: item.createTime,
                                modifyTime: item.modifyTime,
                                status: item.status,
                                normal: item.normal
                            });
                        });
                        this.setState({
                            isSearch: true,
                            searchData: searchData,
                            tableLoading: false,
                            alertVisible: false,
                        });
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });


            }
        });
    }



    handleDetailDrawerCancel() {
        this.setState({
            detailVisible: false,
        })
    }

    //关闭 alert 的提示
    handleClose() {
        this.setState({ alertVisible: false });
    }

    clearAll = () => {
        this.setState({
            filteredInfo: null,
            sortedInfo: null,
        });

    }

    handleChange = (pagination, filters, sorter) => {
        //console.log('Various parameters', pagination, filters, sorter);
        this.setState({
            filteredInfo: filters,
            sortedInfo: sorter,
        });
    }

    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
        // this.setState({
        //     searchText: selectedKeys[0],
        // });
    }

    handleSearchReset = clearFilters => () => {
        clearFilters();
        // this.setState({
        //     searchText: '',
        // });
    }

    clearAll2 = () => {
        this.setState({
            filteredInfo2: null,
            sortedInfo2: null,
        });

    }

    handleChange2 = (pagination, filters, sorter) => {
        //console.log('Various parameters', pagination, filters, sorter);
        this.setState({
            filteredInfo2: filters,
            sortedInfo2: sorter,
        });
    }

    handleSearch2 = (selectedKeys, confirm) => () => {
        confirm();
        // this.setState({
        //     // searchText2: selectedKeys[0],
        // });
    }

    handleSearchReset2 = clearFilters => () => {
        clearFilters();
        // this.setState({
        //     // searchText2: '',
        // });
    }

    onRef = (ref) => {
        this.child = ref
    }

    searchReset = () => {
        this.props.form.resetFields();
        this.setState({
            isSearch: false,
        })
    }

    fullScreenCancel() {
        this.setState({
            fullScreenVisible: false,
        })
    }

    showDetailDrawer(superviseId) {

        this.setState({
            detailVisible:true,
            detailExist:true,
            currentSuperviseId:superviseId,
        })
    }


    render() {
        let { sortedInfo, filteredInfo } = this.state;
        sortedInfo = sortedInfo || {};
        filteredInfo = filteredInfo || {};
        const columns = [{
            title: "序号",
            dataIndex: "key",
            key: "key"
        },
        {
            title: "巡查人员",
            dataIndex: "realname",
            key: "realname",
        },
        {
            title: "巡查学校",
            dataIndex: "schoolname",
            key: "schoolname",
        },
        {
            title: "开始时间",
            dataIndex: "createTime",
            key: "createTime",
        },
        {
            title: "结束时间",
            dataIndex: "modifyTime",
            key: "modifyTime",
        },
        {
            title: "巡查状态",
            dataIndex: "status",
            key: "status",
        },
        {
            title: "异常情况",
            dataIndex: "normal",
            key: "normal",
        },
        ];

        const { getFieldDecorator, getFieldValue } = this.props.form;
        let { sortedInfo2, filteredInfo2 } = this.state;
        sortedInfo2 = sortedInfo2 || {};
        filteredInfo2 = filteredInfo2 || {};


        let keyWidth = undefined;
        let realnameWidth = undefined;
        let schoolnameWidth = undefined;
        let createTimeWidth = undefined;
        let modifyTimeWidth = undefined;
        let statusWidth = undefined;
        let normalWidth = undefined;
        let actionWidth = undefined;
        let winWidth;
        // 获取窗口宽度
        if (window.innerWidth)
            winWidth = window.innerWidth;
        else if ((document.body) && (document.body.clientWidth))
            winWidth = document.body.clientWidth;
        if (winWidth < 1500) {
            keyWidth = 60;
            realnameWidth = 90;
            schoolnameWidth = 150;
            createTimeWidth = 150;
            modifyTimeWidth = 150;
            statusWidth = 90;
            normalWidth = 90;
            actionWidth = 90;
        }

            const columnsSearch = [{
                title: "序号",
                dataIndex: "key",
                key: "key",
                width: keyWidth,
            }, {
                title: "巡查人员",
                dataIndex: "realname",
                key: "realname",
                width: realnameWidth
            }, {
                title: "巡查学校",
                dataIndex: "schoolname",
                key: "schoolname",
                width: schoolnameWidth
            }, {
                title: '开始时间',
                dataIndex: 'createTime',
                key: 'createTime',
                width: createTimeWidth,
                sorter: (a, b) => new Date(a.createTime).getTime() - new Date(b.createTime).getTime(),
                sortOrder: sortedInfo2.columnKey === 'createTime' && sortedInfo2.order,
            }, {
                title: '结束时间',
                dataIndex: 'modifyTime',
                key: 'modifyTime',
                width: modifyTimeWidth,
                sorter: (a, b) => new Date(a.modifyTime).getTime() - new Date(b.modifyTime).getTime(),
                sortOrder: sortedInfo2.columnKey === 'modifyTime' && sortedInfo2.order,
            }, {
                title: "巡查状态",
                dataIndex: "status",
                key: "status",
                width: statusWidth,
                render: (text) => {
                    if (text == '1') { return (<span style={{ color: 'green' }}>进行中</span>) }
                    else if (text == '2') { return (<span style={{ color: 'red' }}>已结束</span>) }
                }
            }, {
                title: "异常情况",
                dataIndex: "normal",
                key: "normal",
                width: normalWidth,
                render: (text) => {
                    if (text != '2') { return (<span style={{ color: 'green' }}>无异常</span>) }
                    else if (text == '2') { return (<span style={{ color: 'red' }}>有异常</span>) }
                },
            }, {
                title: "操作详情",
                key: "action",
                width: actionWidth,
                render: (text, record) => {
                    console.log("===", record)
                        return (
                            <span>
                                <a
                                    href="javascript:;"
                                    onClick={this.showDetailDrawer.bind(this, record.id)}>
                                    查看详情
                                </a>
                            </span>
                        )
                }
            }
        ];



        let labelCol = {
            sm: { span: 6 },
            xl: { span: 6 },
            xxl: { span: 5 },
        };

        let wrapperCol = {
            sm: { span: 18 },
            xl: { span: 18 },
            xxl: { span: 19 },
        };

        return (
            <div style={{ marginBottom: 16 }}>
                <Form
                    style={{
                        padding: '12px',
                        backgroundColor: '#fafafa',
                        borderRadius: 8,
                        marginBottom: 16,
                    }}
                    layout="inline"
                    onSubmit={this.searchSubmit}>
                    <Row>
                        <Col span={11}>
                            <FormItem
                                label="巡查人员"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("realname", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Input
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请输入巡查人员"
                                    ></Input>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={11}>
                            <FormItem
                                label="巡查学校"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("schoolname", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Input
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请输入巡查学校"
                                    ></Input>
                                )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={11}>
                            <FormItem
                                label="截止日期"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("deadline", {
                                    rules: [{
                                        type: 'array',
                                        required: false,
                                    }]
                                })(
                                    <RangePicker
                                        style={{ width: '100%' }}
                                        format="YYYY-MM-DD" />
                                )}
                            </FormItem>
                        </Col>
                        <Col span={11}>
                        <FormItem
                                label="巡查状态"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("status", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请选择巡查状态">
                                        <Option value={1}>进行中</Option>
                                        <Option value={2}>已结束</Option>
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={11}>
                            <FormItem
                                label="异常情况"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("normal", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        placeholder="请选择异常情况">
                                        <Option value={1}>无异常</Option>
                                        <Option value={2}>有异常</Option>
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        <FormItem
                            style={{ float: 'right' }}>
                            <Button type="primary" htmlType="submit">搜索</Button>
                            <Button style={{ marginLeft: 8 }} onClick={this.searchReset}>清空</Button>
                        </FormItem>
                    </Row>
                </Form>
                    <div>
                        <Table
                            dataSource={this.state.searchData}
                            columns={columnsSearch}
                            loading={this.state.tableLoading}
                            locale={{ emptyText: '暂无数据' }}
                            onChange={this.handleChange2}
                            rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                            pagination={{  //分页
                                total: this.state.searchData.length, //数据总数量
                                defaultPageSize: 10, //默认显示几条一页
                                //pageSize: 10,
                                showTotal: function (total) {  //设置显示一共几条数据
                                    return '共 ' + total + ' 条数据';
                                },
                                showSizeChanger: true,
                                showQuickJumper: true,
                                pageSizeOptions: [5, 10, 20, 30]
                            }} />
                            {
                            this.state.detailExist ? (
                                <DailyConditionDetail
                                    visible={this.state.detailVisible}
                                    currentSuperviseId={this.state.currentSuperviseId}
                                    that={this} />
                            ) : null
                        }
                    </div>
            </div>
        )
    }
}
const DailyRecord = Form.create()(dailyRecord);

class DailyConditionDetail extends Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: props.visible,
            currentSuperviseId: props.currentSuperviseId,
            that: props.that,
            confirmLoading: false,
            previewVisible: false,
            previewImage: '',
            detailData: [],
            dealDetailData: [],
        };
    }

    componentDidMount() {
        this.refreshData(this.props.currentSuperviseId);

    }

    componentWillReceiveProps(props) {
        this.setState({
            visible:props.visible,
            currentSuperviseId: props.currentSuperviseId,
            that: props.that,
        })
        if (props.visible) {
            this.refreshData(props.currentSuperviseId);
        }
    }

    refreshData(currentSuperviseId){
        this.setState({
            confirmLoading: true,
        })
        this.getDailyConditionDetail(currentSuperviseId)
        this.getDailyDealDetail(currentSuperviseId)
    }


    getDailyConditionDetail(suddenSuperviseId) {
        getDailyConditionDetailApi(suddenSuperviseId).then((res) => {
            this.setState({
                detailData: res.data
            })
        })
    }

    getDailyDealDetail(suddenSuperviseId) {
        getDailyDealDetailApi(suddenSuperviseId).then((res) => {
            this.setState({
                dealDetailData: res.data
            })
        })
    }

    handlePreview = (src) => {
        this.setState({
            previewImage: src,
            previewVisible: true,
        });
    }

    handlePreviewCancel = () => this.setState({ previewVisible: false })
       
    render() {


        const Panel = Collapse.Panel;
        const gridStyle = {
            width: '33.33333333333333333333333%',
            height: '150px',
            textAlign: 'center',
            position: 'relative'
        };

        let mainPanels = []
        for(let category in this.state.detailData) {
            let header1 = (
                <div style={{ height: '100%', width: '100%' }}>
                    <div style={{ width: '80%', left: 0 }}>
                        {category}
                    </div>
                    <img
                        style={{
                            width: '15%',
                            right: 5,
                            top: 0,
                            bottom: 0,
                            margin: 'auto',
                            position: 'absolute',
                        }}
                        src={require('../img/xuncha2.png')}
                    />
                </div>
            );

            const detailPanels = this.state.detailData[category].map((d, index) => {
                let header2 = (
                    <div style={{ height: '100%', width: '100%' }}>
                        <div style={{ width: '80%', left: 0 }}>
                            {d.content}
                        </div>
                    </div>
                )

            let prePhotos;
            let preVideo;
            if (d.photo == ''|| d.photo == undefined) {
                prePhotos = (
                    <Card.Grid
                        key={0}
                        style={gridStyle}>
                        <img
                            style={{
                                width: 'auto',
                                height: 'auto',
                                position: 'absolute',
                                top: 0,
                                left: 0,
                                right: 0,
                                bottom: 0,
                                margin: 'auto',
                                maxWidth: '100%',
                                maxHeight: '100%',
                                padding: 5,
                            }}
                            alt="暂无图片"
                            src={require('../img/nophoto.png')} />
                    </Card.Grid>
                );
            } else {
                let photoArr = d.photo.split(',')
                prePhotos = (
                    photoArr.map((p, i) => {
                        return(
                            <Card.Grid
                                key={i}
                                style={gridStyle}>
                                <img
                                    style={{
                                        width: 'auto',
                                        height: 'auto',
                                        position: 'absolute',
                                        top: 0,
                                        left: 0,
                                        right: 0,
                                        bottom: 0,
                                        margin: 'auto',
                                        maxWidth: '100%',
                                        maxHeight: '100%',
                                        padding: 5,
                                    }}
                                    alt='异常照片'
                                    src={UrlPrefix + p}
                                   // onClick={this.handlePreview.bind(this, UrlPrefix + p)}
                                     />
                            </Card.Grid>
                        )
                    })
                    
                );
            }
            preVideo = (
                <Card.Grid
                    key={0}
                    style={gridStyle}>
                    <video
                        style={{
                            width: 'auto',
                            height: 'auto',
                            position: 'absolute',
                            top: 0,
                            left: 0,
                            right: 0,
                            bottom: 0,
                            margin: 'auto',
                            maxWidth: '100%',
                            maxHeight: '100%',
                            padding: 5,
                        }}
                        src={UrlPrefix + d.video} controls />
                </Card.Grid>
            );

                let details = [{
                    title: '上报学校',
                    description: d.address,
                }, {
                    title: '上报人',
                    description: d.realname,
                }, {
                    title: '状态',
                    description: d.status,
                }, {
                    title: '上报时间',
                    description: d.createTime
                }, {
                    title: '上报内容',
                    description: d.content,
                }, {
                    title: '上报照片',
                    description: (
                        <Card
                            hoverable
                            style={{ marginTop: '10px' }}>
                               <RViewerJS> 
                            {prePhotos}
                            </RViewerJS>
                        </Card>),
                }, {
                    title: '上报视频',
                    description: (
                        (d.video == ""|| d.video == undefined) ?
                            <span>暂无视频</span>
                            :
                            <Card
                                hoverable
                                style={{ marginTop: '10px' }}>
                                     <RViewerJS> 
                                {preVideo}
                                </RViewerJS> 
                            </Card>
                    ),
                }];

                return(
                    <Panel header={header2} key={index}>
                        <List
                            itemLayout="horizontal"
                            dataSource={details}
                            renderItem={item => (
                                <List.Item>
                                    <List.Item.Meta
                                        title={item.title}
                                        description={item.description}
                                    />
                                </List.Item>
                            )}
                        />
                    </Panel>
                )
            })
            mainPanels.push(
                // 隐患类型面板
                <Panel header={header1} key={category}>
                <Collapse>
                    {detailPanels}
                </Collapse>
                </Panel>
            )
        }
        if(mainPanels.length == 0) {
            mainPanels.push(
                <Panel header='此条暂无隐患信息'></Panel>
            )
        }
        let dealMainPanels = []
        for(let category in this.state.dealDetailData) {
            let header1 = (
                <div style={{ height: '100%', width: '100%' }}>
                    <div style={{ width: '80%', left: 0 }}>
                        {category}
                    </div>
                </div>
            );

            const detailPanels = this.state.dealDetailData[category].map((d, index) => {
                let header2 = (
                    <div style={{ height: '100%', width: '100%' }}>
                        <div style={{ width: '80%', left: 0 }}>
                            {d.content}
                        </div>
                    </div>
                )

            let dealPhotos;
            let dealVideo;
            if (d.dealPhoto == ''|| d.dealPhoto == undefined) {
                dealPhotos = (
                    <Card.Grid
                        key={0}
                        style={gridStyle}>
                        <img
                            style={{
                                width: 'auto',
                                height: 'auto',
                                position: 'absolute',
                                top: 0,
                                left: 0,
                                right: 0,
                                bottom: 0,
                                margin: 'auto',
                                maxWidth: '100%',
                                maxHeight: '100%',
                                padding: 5,
                            }}
                            alt="暂无图片"
                            src={require('../img/nophoto.png')} />
                    </Card.Grid>
                );
            } else {
                let photoArr = d.dealPhoto.split(',')
                dealPhotos = (
                    photoArr.map((p, i) => {
                        return(
                            <Card.Grid
                                key={i}
                                style={gridStyle}>
                                <img
                                    style={{
                                        width: 'auto',
                                        height: 'auto',
                                        position: 'absolute',
                                        top: 0,
                                        left: 0,
                                        right: 0,
                                        bottom: 0,
                                        margin: 'auto',
                                        maxWidth: '100%',
                                        maxHeight: '100%',
                                        padding: 5,
                                    }}
                                    alt='异常照片'
                                    src={UrlPrefix + p}
                                   // onClick={this.handlePreview.bind(this, UrlPrefix + p)}
                                     />
                            </Card.Grid>
                        )
                    })
                    
                );
            }
            dealVideo = (
                <Card.Grid
                    key={0}
                    style={gridStyle}>
                    <video
                        style={{
                            width: 'auto',
                            height: 'auto',
                            position: 'absolute',
                            top: 0,
                            left: 0,
                            right: 0,
                            bottom: 0,
                            margin: 'auto',
                            maxWidth: '100%',
                            maxHeight: '100%',
                            padding: 5,
                        }}
                        src={UrlPrefix + d.dealVideo} controls />
                </Card.Grid>
            );

                let details = [{
                    title: '处理人',
                    description: d.realname,
                }, {
                    title: '处理时间',
                    description: d.createTime
                }, {
                    title: '处理内容',
                    description: d.dealContent,
                }, {
                    title: '处理照片',
                    description: (
                        <Card
                            hoverable
                            style={{ marginTop: '10px' }}>
                                <RViewerJS>
                            {dealPhotos}
                            </RViewerJS>
                        </Card>),
                }, {
                    title: '处理视频',
                    description: (
                        (d.dealVideo == ""|| d.dealVideo == undefined) ?
                            <span>暂无视频</span>
                            :
                            <Card
                                hoverable
                                style={{ marginTop: '10px' }}>
                                     <RViewerJS>
                                {dealVideo}
                                </RViewerJS>
                            </Card>
                    ),
                }];

                return(
                    <Panel header={header2} key={index}>
                        <List
                            itemLayout="horizontal"
                            dataSource={details}
                            renderItem={item => (
                                <List.Item>
                                    <List.Item.Meta
                                        title={item.title}
                                        description={item.description}
                                    />
                                </List.Item>
                            )}
                        />
                    </Panel>
                )
            })
            dealMainPanels.push(
                // 隐患类型面板
                <Panel header={header1} key={category}>
                <Collapse>
                    {detailPanels}
                </Collapse>
                </Panel>
            )
        }
        if(dealMainPanels.length == 0) {
            dealMainPanels.push(
                <Panel header='此条暂无处理信息'></Panel>
            )
        }
        return (
            <div>
                <Drawer
                    bodyStyle={{ paddingBottom: 80 }}
                    width={800}
                    title='日常巡查内容详情'
                    visible={this.state.visible}
                    onClose={this.state.that.handleDetailDrawerCancel.bind(this.state.that)}
                    destroyOnClose={true}
                    closable
                >
                    <Tabs
                        defaultActiveKey="1">
                        <TabPane tab={<span ><IconFont type="icon-weiwancheng" className='iconTabs' />上报信息</span>} key="1">
                            <Collapse>
                                {mainPanels}
                            </Collapse>
                        </TabPane>
                        <TabPane tab={<span ><IconFont type="icon-yiwanchengdingdan" className='iconTabs' />处理信息</span>} key="2">
                            <Collapse>
                                {dealMainPanels}
                            </Collapse>
                        </TabPane>
                    </Tabs>
                    <div
                        style={{
                            position: 'absolute',
                            left: 0,
                            bottom: 0,
                            width: '100%',
                            borderTop: '1px solid #e9e9e9',
                            padding: '10px 16px',
                            background: '#fff',
                            textAlign: 'right',
                        }}
                    >
                        <Button size="large" onClick={this.state.that.handleDetailDrawerCancel.bind(this.state.that)}
                            style={{ marginRight: 20 }}>关闭</Button>
                    </div>
                </Drawer>
                <Modal
                    destroyOnClose
                    visible={this.state.previewVisible}
                    footer={null}
                    bodyStyle={{
                        paddingTop: 48,
                    }}
                    onCancel={this.handlePreviewCancel}>
                    <img
                        alt="照片"
                        style={{ width: '100%' }}
                        src={this.state.previewImage} />
                </Modal>
            </div>

        );
    }
}

class xunchaPlan extends Component{
    constructor(props){
        super(props);
        this.state={
            parentId:undefined, //是否为市级教育局
            parentIdtest:1,
            addVisible: false, //控制新增模态框显示隐藏
            updateUserVisible: false, //控制修改用户信息模态框显示隐藏
            alertVisible: false, //提示用户名已存在
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            // searchText: '',
            tableLoading: true,
            identityFilter: [],
            columnData: [],
            filteredInfo: null,
            sortedInfo: null,
            exportUserInfoVisible: false,
            classname: '',
            themeId:-1,
            fileList: [],
            uploading: false,
            test:"test",
            updaterecord:undefined,
            theme:'',
            isUseVisible:false,
            isUseVisible2:false,
            isUserecord:undefined,
            detailVisible: false,
            detailExist: false,
            DrawerIsuse:undefined
        }
    }

    componentDidMount(){
this.refreshData();
    }
    refreshData(){
        this.setState({
            tableLoading: true
        });
        let columnData = [];
        let departmentId
        if(sessionStorage.getItem("departmentType") == "教育局"){
            departmentId = -parseInt(sessionStorage.getItem("departmentId"))
        }else{
            departmentId = parseInt(sessionStorage.getItem("departmentId"))
        }
        
        getXunchaPlanApi(departmentId)
        .then((res)=>{
            res.data.forEach((item, index)=>{
                columnData.push({
                    key:index + 1,
                    id:item.id,
                    theme:item.theme,
                    userId:item.userId,
                    startTime:item.startTime,
                    endTime:item.endTime,
                    status:item.status,
                    type:item.type,
                    typename:item.typename,
                    realname:item.realname,
                    isuse:item.isuse,
                    isdone:item.isdone,
                    cycle:item.cycle,
                    plantimes:item.plantimes
                });
            });
            this.setState({
                columnData:columnData,
                tableLoading:false
            });
        })
        .catch((e) => {
            if (e.response) {
                //请求已发出，服务器返回状态码不是2xx。
                console.info(e.response.data)
                console.info(e.response.status)
                console.info(e.response.headers)
            } else if (e.request) {
                // 请求已发出，但没有收到响应
                // e.request 在浏览器里是一个XMLHttpRequest实例，
                // 在node中是一个http.ClientRequest实例
                console.info(e.request)
            } else {
                //发送请求时异常，捕捉到错误
                console.info('error', e.message)
            }
            console.info(e.config)
        });


        getDepartmentParentApi(parseInt(sessionStorage.getItem("departmentId")))
        .then((res)=>{
            this.setState({
                parentId:res.data
            })
        })

    }

    handleDelete(record){
        console.log("test", record);
        deleteXunchaPlanApi(record.id, record.type)
        .then((res)=>{
            if (res.data == "success") {
                message.success("删除成功!");
                this.refreshData();
            } else {
                message.error('删除失败,请稍后再试!');
            }
        })
        .catch((e) => {
            if (e.response) {
                //请求已发出，服务器返回状态码不是2xx。
                console.info(e.response.data)
                console.info(e.response.status)
                console.info(e.response.headers)
            } else if (e.request) {
                // 请求已发出，但没有收到响应
                // e.request 在浏览器里是一个XMLHttpRequest实例，
                // 在node中是一个http.ClientRequest实例
                console.info(e.request)
            } else {
                //发送请求时异常，捕捉到错误
                console.info('error', e.message)
            }
            console.info(e.config)
        });
    }
     //关闭 用户名已存在 的提示
     handleClose() {
        this.setState({ alertVisible: false, exportUserInfoVisible: false });
    }
    //关闭模态框
    handleCancel(modal) {
        this.setState({
            alertVisible: false,
            exportUserInfoVisible: false
        });
        if (modal == "addUser") {
            // let val = this.refs.addDutyWeekPlaceForm;
            // val.resetFields();
            this.setState({
                addVisible: false
            });
        }
        if (modal == "updateUser") {
            let val = this.refs.updateXunchaPlanForm;
            val.resetFields();
            this.setState({
                updateUserVisible: false
            });
        }
        if (modal == "isUse") {
            let val = this.refs.isUsePlanForm;
            val.resetFields();
            this.setState({
                isUseVisible: false
            });
        }
        if (modal == "isUse2") {
            
            this.setState({
                isUseVisible2: false
            });
        }
    }
    //点击表格中 修改触发的操作
    updateHandleClick(record) {
        console.log(record);
        this.setState({
            updateUserVisible: true,
            alertVisible: false,
            exportUserInfoVisible: false,
            updaterecord:record,
            theme:record.theme
        });
        // console.log("test", this.state.updaterecord);
        // console.log("test2", this.state.updaterecord.theme);
        
    }
     //修改巡查计划信息 点击提交按钮后的操作
     updateplanHandleClick(record) {
         console.log("record", record);
        this.setState({
            confirmLoading: true,
            exportUserInfoVisible: false
        });
        let val = this.refs.updateXunchaPlanForm;
        val.validateFields((err, values) => {
            
             values.starttime=moment(values.starttime).format('YYYY-MM-DD');
             values.endtime=moment(values.endtime).format('YYYY-MM-DD');
             console.log("===================", values);
             if (!err) {
            updateXunchaPlanApi(record.id, record.type, values, record.cycle)
                .then((res) => {
                    if (res.data == "success") {
                        this.setState({
                            updateUserVisible: false,
                            confirmLoading: false
                        });
                        this.refreshData();
                        message.success("更新成功!");
                        val.resetFields();
                    } else if (res.data == "fail") {
                        this.setState({
                            alertVisible: true,
                            updateUserVisible: true,
                            confirmLoading: false,
                            msg: "修改失败,请检查信息或稍后再试!"
                        });
                    }
                    else if (res.data == "err") {
                        this.setState({
                            alertVisible: true,
                            updateUserVisible: true,
                            confirmLoading: false,
                            msg: "开始时间不能晚于结束时间!"
                        });
                    }

                })
                .catch((e) => {
                    if (e.response) {
                        //请求已发出，服务器返回状态码不是2xx。
                        console.info(e.response.data)
                        console.info(e.response.status)
                        console.info(e.response.headers)
                    } else if (e.request) {
                        // 请求已发出，但没有收到响应
                        // e.request 在浏览器里是一个XMLHttpRequest实例，
                        // 在node中是一个http.ClientRequest实例
                        console.info(e.request)
                    } else {
                        //发送请求时异常，捕捉到错误
                        console.info('error', e.message)
                    }
                    console.info(e.config)
                });
            }else {
                this.setState({
                    confirmLoading: false
                });
            }

        });
        
    }
    //发布计划 点击提交后的操作
    isUseHandleClick(record){
        this.setState({
            confirmLoading: true,
            exportUserInfoVisible: false
        });
        let val = this.refs.isUsePlanForm;
        val.validateFields((err, values)=>{
            if(!err){
                addXunchaPlanForDepartmentApi(record, values)
                .then((res) => {
                    if (res.data == "success") {
                        this.setState({
                            isUseVisible: false,
                            confirmLoading: false
                        });
                        this.refreshData();
                        message.success("发布成功!");
                        val.resetFields();
                    } else if (res.data == "fail") {
                        this.setState({
                            alertVisible: true,
                            isUseVisible: true,
                            confirmLoading: false,
                            msg: "发布失败！"
                        });
                    }
                    else if (res.data == "err") {
                        this.setState({
                            alertVisible: true,
                            isUseVisible: true,
                            confirmLoading: false,
                            msg: "开始时间不能晚于结束时间!"
                        });
                    }

                })
                .catch((e) => {
                    if (e.response) {
                        //请求已发出，服务器返回状态码不是2xx。
                        console.info(e.response.data)
                        console.info(e.response.status)
                        console.info(e.response.headers)
                    } else if (e.request) {
                        // 请求已发出，但没有收到响应
                        // e.request 在浏览器里是一个XMLHttpRequest实例，
                        // 在node中是一个http.ClientRequest实例
                        console.info(e.request)
                    } else {
                        //发送请求时异常，捕捉到错误
                        console.info('error', e.message)
                    }
                    console.info(e.config)
                });
            }else {
                this.setState({
                    confirmLoading: false
                });
            }
            
        })
    }
    showAddModal = () => {
        this.setState({
            addVisible: true,
            
        });
    }
    HandleClickIsuse(record){
        if(this.state.parentId==0){
            console.log("testss", record);
            console.log(record.isuse)
        this.setState({
            isUseVisible: true,
            alertVisible: false,
            exportUserInfoVisible: false,
            isUserecord:record,
            
        });
        }
        else{
            this.setState({
                isUseVisible2: true,
                alertVisible: false,
                exportUserInfoVisible: false,
                isUserecord:record,
                
            });
        }
        
    }
    showDetailDrawer(record){
        
        this.setState({
            detailExist: true,
            detailVisible: true,
            DrawerIsuse:record.isuse,
            themeId:record.id
        })
        console.log("ss", this)
        console.log("ss", this.state.themeId)
        console.log("ss2", record)
    }
    handleDetailDrawerCancel() {
        this.setState({
            detailVisible: false
            
        })
    }
    isUseHandleClick2(record){
        console.log("test", record);
        IsUseForDepartment(record)
        .then((res)=>{
            if (res.data == "success") {
                this.setState({
                    isUseVisible2: false,
                    confirmLoading: false
                });
                this.refreshData();
                message.success("发布成功!");
               
            } else if (res.data == "fail") {
                this.setState({
                    alertVisible: true,
                    isUseVisible2: true,
                    confirmLoading: false,
                    msg: "发布失败！"
                });
            }
        })
        .catch((e) => {
            if (e.response) {
                //请求已发出，服务器返回状态码不是2xx。
                console.info(e.response.data)
                console.info(e.response.status)
                console.info(e.response.headers)
            } else if (e.request) {
                // 请求已发出，但没有收到响应
                // e.request 在浏览器里是一个XMLHttpRequest实例，
                // 在node中是一个http.ClientRequest实例
                console.info(e.request)
            } else {
                //发送请求时异常，捕捉到错误
                console.info('error', e.message)
            }
            console.info(e.config)
        });
    }

    //新增巡查计划
    handleAddXunchaPlan(){
        this.setState({
            confirmLoading: true
        });
        let val = this.refs.addXunchaPlanForm;
        val.validateFields((err, values) => {
            values.starttime=moment(values.starttime).format('YYYY-MM-DD');
            values.endtime=moment(values.endtime).format('YYYY-MM-DD');
            console.log("test", values)
            if(!err){
                addXunchaPlanApi(parseInt(sessionStorage.getItem("userId")), parseInt(sessionStorage.getItem("departmentId")), values)
                .then((res)=>{
                    if (res.data == "success") {
                        this.setState({
                            addVisible: false,
                            confirmLoading: false
                        });
                        this.refreshData();
                        message.success("添加成功!");
                        val.resetFields();
                    } else if (res.data == "fail") {
                        this.setState({
                            alertVisible: true,
                            addVisible: true,
                            confirmLoading: false,
                            msg: "添加失败,请检查填写信息!"
                        });
                    }
                    else if (res.data == "err") {
                        this.setState({
                            alertVisible: true,
                            addVisible: true,
                            confirmLoading: false,
                            msg: "添加失败,存在重复计划或开始时间晚于结束时间!"
                        });
                    }
                }).catch((e) => {
                    if (e.response) {
                        //请求已发出，服务器返回状态码不是2xx。
                        console.info(e.response.data)
                        console.info(e.response.status)
                        console.info(e.response.headers)
                    } else if (e.request) {
                        // 请求已发出，但没有收到响应
                        // e.request 在浏览器里是一个XMLHttpRequest实例，
                        // 在node中是一个http.ClientRequest实例
                        console.info(e.request)
                    } else {
                        //发送请求时异常，捕捉到错误
                        console.info('error', e.message)
                    }
                    console.info(e.config)
                });
            }
            else {
                this.setState({
                    confirmLoading: false
                });
            }
        })
        
    }
    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
        // this.setState({
        //     searchTextAddress: selectedKeys[0],
        //     searchTextReporter: selectedKeys[0]
        // });
    }
    handleSearchReset = clearFilters => () => {
        clearFilters();
        // this.setState({
        //     searchTextAddress: '',
        //     searchTextReporter: '',
        // });
    }
    render(){
        const userColumns = [
            {
                title: "序号",
                dataIndex: "key",
                key: "key"
            },
            {
                title: "主题",
                dataIndex: "theme",
                key: "theme",
                filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                    <div className="custom-filter-dropdown">
                        <Input
                            ref={ele => this.searchInput = ele}
                            value={selectedKeys[0]}
                            onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                            onPressEnter={this.handleSearch(selectedKeys, confirm)}
                        />
                        <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                        <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                    </div>
                ),
                filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
                onFilter: (value, record) => record.theme.toLowerCase().includes(value.toLowerCase()),
                onFilterDropdownVisibleChange: (visible) => {
                    if (visible) {
                        setTimeout(() => {
                            this.searchInput.focus();
                        });
                    }
                }
            },
            {
                title: "开始时间",
                dataIndex: "startTime",
                key: "startTime",
                sorter: (a, b) => new Date(a.startTime).getTime() - new Date(b.startTime).getTime(),
            },
            {
                title: "结束时间",
                dataIndex: "endTime",
                key: "endTime",
                sorter: (a, b) => new Date(a.endTime).getTime() - new Date(b.endTime).getTime(),
            },
            {
                title: "创建人",
                dataIndex: "realname",
                key: "realname",
                filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                    <div className="custom-filter-dropdown">
                        <Input
                            ref={ele => this.searchInput = ele}
                            value={selectedKeys[0]}
                            onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                            onPressEnter={this.handleSearch(selectedKeys, confirm)}
                        />
                        <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                        <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                    </div>
                ),
                filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
                onFilter: (value, record) => record.realname.toLowerCase().includes(value.toLowerCase()),
                onFilterDropdownVisibleChange: (visible) => {
                    if (visible) {
                        setTimeout(() => {
                            this.searchInput.focus();
                        });
                    }
                }
            },
            {
                title: "任务类型",
                dataIndex: "typename",
                key: "typename",
                filters: [
                    {
                      text: '专项巡查',
                      value: '专项巡查',
                    },
                    {
                      text: '定期巡查',
                      value: '定期巡查',
                    },
                  ],
                  onFilter: (value, record) => record.typename.indexOf(value) === 0,
            },
            {
                title: "周期",
                dataIndex: "cycle",
                key: "cycle",
                filters: [
                    {
                      text: '专项',
                      value: '专项',
                    },
                    {
                      text: '每月',
                      value: '每月',
                    },
                    {
                        text: '季度',
                        value: '季度',
                      },
                      {
                        text: '半年',
                        value: '半年',
                      },
                  ],
                  onFilter: (value, record) => record.cycle.indexOf(value) === 0,
            },
            {
                title: "计划执行次数",
                dataIndex: "plantimes",
                key: "plantimes",
            },
            {
                title: "操作详情",
                key: "action",
                dataIndex: "isuse",
                
                render: (isuse, record) => (
                    <span>
                        {isuse==0?
                        (<span><a href="javascript:;"
                        onClick={() => this.updateHandleClick(record)} 
                        >修改</a>
                       <Divider type="vertical" />

                       <Popconfirm title="确定删除？" okText="确定" cancelText="取消"
                           onConfirm={() => this.handleDelete(record)}
                           >
                           <a href="#">删除</a>
                       </Popconfirm></span>)
                        :
                        ("已发布，无法修改与删除")}
                    
                        
                    </span>
                )
            },
            {
                title:"巡查内容",
                key:"xuncha_content",
                dataIndex: "isuse",
                render:(isuse, record)=>(
                    <Button type="primary" size="large" onClick={this.showDetailDrawer.bind(this, record)}
                    >{isuse==0?
                        ("修改")
                        :
                        ("查看")}</Button>
                )
            },
            {
                title: "发布状态",
                key: "isuse",
                dataIndex: "isuse",
                
                render: (isuse, record) => (
                    
                    <Button key="submit" type="primary" size="large" disabled={isuse}
                    onClick={this.HandleClickIsuse.bind(this, record)}
                    >{isuse==0?
                        (<span>发&nbsp;&nbsp;&nbsp;布</span>)
                        :
                        ("已发布")}</Button>
                ),
                filters: [
                    {
                      text: '已发布',
                      value: 1,
                    },
                    {
                      text: '未发布',
                      value: 0,
                    },
                   
                  ],
                  onFilter: (value, record) => record.isuse==value,
            }
        ]
        return(
            <div>
                <div style={{marginBottom: 15}}>
                <Button type="primary" 
                onClick={()=>this.showAddModal()}
                 size="large" style={{ marginLeft: 15 }}> 新增巡查计划</Button>
                 <Modal
                 title={"新增巡检计划"}
                 closable={true}
                 centered
                 destroyOnClose={true}
                 visible={this.state.addVisible}
                 onCancel={this.handleCancel.bind(this, "addUser")}
                 footer={[
                    <Button key="submit" type="primary" size="large"
                        loading={this.state.confirmLoading}
                        onClick={this.handleAddXunchaPlan.bind(this)}
                        >提交</Button>
                ]}>
                    <AddXunchaPlanForm ref="addXunchaPlanForm"  />

                        {
                            this.state.alertVisible ?
                                (
                                    <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                                ) : null
                        }
                </Modal>
                </div>
                <Alert style={{display: 'table', marginLeft: 15, marginTop:10, marginBottom:15}} message="点击发布按钮后，将无法对计划进行修改或删除" type="info" showIcon/> 
                <Modal
                        title="修改巡查计划"
                        visible={this.state.updateUserVisible}
                        onCancel={this.handleCancel.bind(this, "updateUser")}
                        closable
                        footer={[
                            <Button key="submit" type="primary" size="large"
                                loading={this.state.confirmLoading}
                                onClick={this.updateplanHandleClick.bind(this, this.state.updaterecord)}
                                >提交</Button>
                        ]}
                    >

                        <UpdateXunchaPlanForm ref="updateXunchaPlanForm" record={this.state.updaterecord} />

                        {
                            this.state.alertVisible ?
                                (
                                    <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                                ) : null
                        }
                    </Modal>
                    <Modal
                        title="发布详情"
                        visible={this.state.isUseVisible}
                        onCancel={this.handleCancel.bind(this, "isUse")}
                        closable
                        footer={[
                            <Button key="submit" type="primary" size="large"
                                loading={this.state.confirmLoading}
                                onClick={this.isUseHandleClick.bind(this, this.state.isUserecord)}
                                >提交</Button>
                        ]}
                    >

                        <IsUsePlanForm ref="isUsePlanForm"  record={this.state.isUserecord}/>

                        {
                            this.state.alertVisible ?
                                (
                                    <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                                ) : null
                        }
                    </Modal>
                    <Modal
                        title="发布详情"
                        visible={this.state.isUseVisible2}
                        onCancel={this.handleCancel.bind(this, "isUse2")}
                        closable
                        onOk={this.isUseHandleClick2.bind(this, this.state.isUserecord)} 
                    >
                        <p style={{ alignContent:"center"}}>是否发布计划</p>

                        {
                            this.state.alertVisible ?
                                (
                                    <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                                ) : null
                        }
                    </Modal>
                <Table
                    dataSource={this.state.columnData}
                    columns={userColumns}
                    //loading={this.state.tableLoading}
                    locale={{ emptyText: '暂无数据' }}
                    //onChange={this.handleChange}
                    rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                    pagination={{  //分页
                        defaultPageSize: 10, //默认显示几条一页
                        //pageSize: 10,
                        showTotal: function (total) {  //设置显示一共几条数据
                            return '共 ' + total + ' 条数据';
                        },
                        showSizeChanger: true,
                        showQuickJumper: true,
                        pageSizeOptions: [5, 10, 20, 30]
                    }} 
                    
                    // expandedRowRender={(record) => {    
                    //     return (
                    //         <XunchaInnerTable
                    //             // onRef={this.onRef}
                    //              superviseId={record.id}
                    //             that={this} />)}
                    //         }
                    // rowExpandable={false}
                    // // ={(record)=>{
                    // //    return false
                       
                    // // }}
                    // expandable={{
                    //     expandedRowRender: record =>  <p>{record.theme}</p>,
                    //     rowExpandable: record => record.key !== 1,
                    //   }}
                    />
                      {
                    this.state.detailExist ? (
                        <XunchaContentDetail
                            visible={this.state.detailVisible}
                            DrawerIsuse={this.state.DrawerIsuse}
                            themeId={this.state.themeId}
                            that={this} />
                    ) : null
                }
            </div>
            
        )
    }
}
//巡查内容划窗
class XunchaContentDetail extends Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: props.visible,
            DrawerIsuse:props.DrawerIsuse,
            themeId:props.themeId,
            that: props.that,
            treeData: [],
            checkedKeys: [],
            selectAll: [],
            confirmLoading: false,
            expandedKeys: [],
            msg: "", //提交失败时的提示语
            selectedKeys: [],
            autoExpandParent: true,
            
        };
        //console.log('currentInspectPlanIds', props.currentInspectPlanIds)
    }

    componentDidMount() {
        
        
        this.setState({
            themeId:this.state.themeId,
        })
        
            this.refreshData(this.state.themeId);
    
        
    }



    componentWillReceiveProps(props) {
        

        this.setState({
            
            visible: props.visible,
            DrawerIsuse:props.DrawerIsuse,
            that: props.that,
            
            
        });
        if (props.visible) {
            this.setState({
                themeId:props.themeId,
            })
           
            this.refreshData(props.themeId);
        }
    }

    refreshData(id) {
       
        this.setState({
            confirmLoading: true,
        })
        getXunchaContentApi(id)
        .then((res)=>{
            console.log("test", res.data);
            let treeData = [];
            let checkedKeys = [];
            let selectAll = [];
                
            res.data.forEach((value, i)=>{
                let item={
                    title: value.content,
                    key:value.contentId
                }
                treeData.push(item);
                if(value.isUse==1){
                    checkedKeys.push(value.contentId)
                }
                selectAll.push(value.contentId)
            })

            this.setState({
                treeData: treeData,
                confirmLoading: false,
                selectAll: selectAll,
                checkedKeys: checkedKeys,

            });

        })
        .catch((e) => {
            if (e.response) {
                //请求已发出，服务器返回状态码不是2xx。
                console.info(e.response.data)
                console.info(e.response.status)
                console.info(e.response.headers)
            } else if (e.request) {
                // 请求已发出，但没有收到响应
                // e.request 在浏览器里是一个XMLHttpRequest实例，
                // 在node中是一个http.ClientRequest实例
                console.info(e.request)
            } else {
                //发送请求时异常，捕捉到错误
                console.info('error', e.message)
            }
            console.info(e.config)
        });
        
            
           
    }

    onChange = (e) => {


        if (e.target.checked) {

            this.setState({
                checkedKeys: this.state.selectAll

            })

        }


        else {


            this.setState({
                checkedKeys: []

            })


        }

    }
    onExpand = (expandedKeys) => {
        this.setState({
            expandedKeys,
            autoExpandParent: false,
        });
    }
    onCheck = (checkedKeys) => {
        //console.log('onCheck', checkedKeys);
        this.setState({ checkedKeys });
        console.log("checkedKeys" + checkedKeys)
    }

    onSelect = (selectedKeys, info) => {
        console.log('onSelect', info);
        this.setState({ selectedKeys });
    }


    //修改巡查内容
    handleUpdateClick() {
        this.setState({
            confirmLoading: true
        });
        console.log("====", this.state.checkedKeys)
        addContentItemApi(parseInt(this.state.themeId), this.state.checkedKeys)
        .then((res)=>{
            if (res.data == "success") {
                message.success("更新成功!");
                this.setState({
                    confirmLoading: false
                });
                this.state.that.handleDetailDrawerCancel();
                this.state.that.refreshData();
            } else if (res.data == "fail") {
                this.setState({
                    alertVisible: true,
                    confirmLoading: false,
                    msg: "修改失败,请检查信息或稍后再试!"
                });
            }
        })
    }
    
   
   
    renderTreeNodes = data => data.map((item) => {
        if (item.children) {
            let color = { color: "#000000" };
            if (item.schoolId != undefined) {
                if (item.schoolId == 0) { color = { color: "#000000" } }
                else if (item.schoolId != 0) { color = { color: "#FF9966" } }
            }
            if (item)
                return (
                    <TreeNode title={item.title} key={item.key} dataRef={item}>
                        {this.renderTreeNodes(item.children)}
                    </TreeNode>
                );
        }
        return <TreeNode {...item} />;
    })

    render() {
        

        const Panel = Collapse.Panel;
        const gridStyle = {
            width: '33.33333333333333333333333%',
            height: '150px',
            textAlign: 'center',
            position: 'relative'
        };

       

       

        

        return (
            <div>

                <Drawer
                    bodyStyle={{ paddingBottom: 80 }}
                    width={1100}
                    title='巡查内容'
                    visible={this.state.visible}
                    onClose={this.state.that.handleDetailDrawerCancel.bind(this.state.that)}
                    destroyOnClose={true}
                    closable
                >
                    <Skeleton loading={this.state.confirmLoading} active>
                    <Checkbox onChange={this.onChange} disabled={this.state.DrawerIsuse} checked={this.state.checkedKeys.length == this.state.treeData.length ? true : false}>全部</Checkbox>
                    <div>
                        
                        <Tree
                        checkable
                        disabled={this.state.DrawerIsuse}
                        onExpand={this.onExpand}
                        expandedKeys={this.state.expandedKeys}
                        autoExpandParent={this.state.autoExpandParent}
                        onCheck={this.onCheck}
                        checkedKeys={this.state.checkedKeys}
                        onSelect={this.onSelect}
                        selectedKeys={this.state.selectedKeys}
                        
                    >
                        {this.renderTreeNodes(this.state.treeData)}
                    </Tree>
                        
                    
                    </div>
                    
                    {/* {
                        this.state.alertVisible ?
                            (
                                <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                            ) : null
                    } */}
                </Skeleton>

                    {this.state.DrawerIsuse==1 ?
                    (<div
                        style={{
                            position: 'absolute',
                            left: 0,
                            bottom: 0,
                            width: '100%',
                            borderTop: '1px solid #e9e9e9',
                            padding: '10px 16px',
                            background: '#fff',
                            textAlign: 'right',
                        }}
                    >
                        
                        <Button size="large" onClick={this.state.that.handleDetailDrawerCancel.bind(this.state.that)}
                            style={{ marginRight: 20 }}>关闭</Button>
                    </div>)
                    :
                    (<div
                        style={{
                            position: 'absolute',
                            left: 0,
                            bottom: 0,
                            width: '100%',
                            borderTop: '1px solid #e9e9e9',
                            padding: '10px 16px',
                            background: '#fff',
                            textAlign: 'right',
                        }}
                    >
                        <Row type="flex" justify="space-around" align="middle">
                            {/* <Col span={18}>
                                <Alert style={{ textAlign: "left" }} message="打勾表示已为巡查任务配置该项，再次点击复选框决定本次是否配置该项。" type="info" showIcon />
                            </Col> */}
                            <Col span={21}>
                                <Button size="large" onClick={this.state.that.handleDetailDrawerCancel.bind(this.state.that)} >关闭</Button>
                            </Col>
                            <Col span={3}>
                                <Button type="primary" size="large" loading={this.state.confirmLoading}
                                   onClick={this.handleUpdateClick.bind(this)} >保存</Button>
                            </Col>
                        </Row>
    
                    </div>)
                }


                    
                </Drawer>
                
            </div>

        );
    }
}
class XunchaInnerTable extends Component{
    constructor(props){
        super(props);
        this.state={
            superviseId:props.superviseId,
            addUserVisible: false, //控制新增用户模态框显示隐藏
            updateUserVisible: false, //控制修改用户信息模态框显示隐藏
            alertVisible: false, //提示用户名已存在
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            // searchText: '',
            tableLoading: true,
            identityFilter: [],
            columnData: [],
            filteredInfo: null,
            sortedInfo: null,
            exportUserInfoVisible: false,
            classname: '',
            addVisible: false,
            fileList: [],
            uploading: false,
            test:"test",
            updaterecord:undefined,
            theme:''
        }
    }
    componentDidMount() {
        this.refreshData();
        //this.props.onRef(this);
    }
    // componentWillReceiveProps(props) {
    //     // console.log('props', props)
    //     this.setState({
    //         gridId: props.gridId,
    //         that: props.that,
    //     });
    //     this.refreshData();
    // }
    onRef = (ref) => {
        this.child = ref
    }
    refreshData(){
        this.setState({
            tableLoading: true
        });
        let columnData = [];
        getDingshiPlanApi(this.state.superviseId)
        .then((res)=>{
            res.data.forEach((item, index)=>{
                columnData.push({
                    key:index + 1,
                    id:item.id,
                    theme:item.theme,
                    userId:item.userId,
                    startTime:item.startTime,
                    endTime:item.endTime,
                    status:item.status,
                    type:item.type,
                    realname:item.realname
                });
            });
            this.setState({
                columnData:columnData,
                tableLoading:false
            });
        })
    }
    handleDelete(record){
        console.log("test", record);
        deleteXunchaPlanApi(record.id, record.type)
        .then((res)=>{
            if (res.data == "success") {
                message.success("删除成功!");
                this.refreshData();
            } else {
                message.error('删除失败,请稍后再试!');
            }
        })
        .catch((e) => {
            if (e.response) {
                //请求已发出，服务器返回状态码不是2xx。
                console.info(e.response.data)
                console.info(e.response.status)
                console.info(e.response.headers)
            } else if (e.request) {
                // 请求已发出，但没有收到响应
                // e.request 在浏览器里是一个XMLHttpRequest实例，
                // 在node中是一个http.ClientRequest实例
                console.info(e.request)
            } else {
                //发送请求时异常，捕捉到错误
                console.info('error', e.message)
            }
            console.info(e.config)
        });
    }
    //关闭模态框
    handleCancel(modal) {
        this.setState({
            alertVisible: false,
            exportUserInfoVisible: false
        });
        if (modal == "addUser") {
            // let val = this.refs.addDutyWeekPlaceForm;
            // val.resetFields();
            this.setState({
                addUserVisible: false
            });
        }
        if (modal == "updateUser") {
            let val = this.refs.updateDingshiPlanForm;
            val.resetFields();
            this.setState({
                updateUserVisible: false
            });
        }
    }
     //点击表格中 修改触发的操作
     updateHandleClick(record) {
        console.log(record);
        this.setState({
            updateUserVisible: true,
            alertVisible: false,
            exportUserInfoVisible: false,
            updaterecord:record,
            theme:record.theme
        });
        // console.log("test", this.state.updaterecord);
        // console.log("test2", this.state.updaterecord.theme);
        
    }
    
     //修改巡查计划信息 点击提交按钮后的操作
     updateplanHandleClick(record) {
        this.setState({
            confirmLoading: true,
            exportUserInfoVisible: false
        });
        let val = this.refs.updateDingshiPlanForm;
        val.validateFields((err, values) => {
            
             values.starttime=moment(values.starttime).format('YYYY-MM-DD');
             values.endtime=moment(values.endtime).format('YYYY-MM-DD');
             console.log("===================", values);
             if (!err) {
            updateDingshiPlanApi(this.state.updaterecord.id, values)
                .then((res) => {
                    if (res.data == "success") {
                        this.setState({
                            updateUserVisible: false,
                            confirmLoading: false
                        });
                        this.refreshData();
                        message.success("更新成功!");
                        val.resetFields();
                    } else if (res.data == "fail") {
                        this.setState({
                            alertVisible: true,
                            updateUserVisible: true,
                            confirmLoading: false,
                            msg: "修改失败,请检查信息或稍后再试!"
                        });
                    }
                })
                .catch((e) => {
                    if (e.response) {
                        //请求已发出，服务器返回状态码不是2xx。
                        console.info(e.response.data)
                        console.info(e.response.status)
                        console.info(e.response.headers)
                    } else if (e.request) {
                        // 请求已发出，但没有收到响应
                        // e.request 在浏览器里是一个XMLHttpRequest实例，
                        // 在node中是一个http.ClientRequest实例
                        console.info(e.request)
                    } else {
                        //发送请求时异常，捕捉到错误
                        console.info('error', e.message)
                    }
                    console.info(e.config)
                });
            }else {
                this.setState({
                    confirmLoading: false
                });
            }

        });
        
    }
    render(){
        const userColumns = [
            {
                title: "序号",
                dataIndex: "key",
                key: "key"
            },
            {
                title: "主题",
                dataIndex: "theme",
                key: "theme"
            },
            {
                title: "创建时间",
                dataIndex: "startTime",
                key: "startTime"
            },
            {
                title: "结束时间",
                dataIndex: "endTime",
                key: "endTime"
            },
            {
                title: "创建人",
                dataIndex: "realname",
                key: "realname"
            },
            
            {
                title: "操作详情",
                key: "action",
                render: (text, record) => (
                    <span>
                        <a href="javascript:;"
                         onClick={() => this.updateHandleClick(record)}
                         >修改</a>
                        <Divider type="vertical" />

                        <Popconfirm title="确定删除？" okText="确定" cancelText="取消"
                            onConfirm={() => this.handleDelete(record)}
                            >
                            <a href="#">删除</a>
                        </Popconfirm>
                    </span>
                )
            }
        ]
        return(
            <div>
                
                <Modal
                        title="修改定期任务主题"
                        visible={this.state.updateUserVisible}
                        onCancel={this.handleCancel.bind(this, "updateUser")}
                        closable
                        footer={[
                            <Button key="submit" type="primary" size="large"
                                loading={this.state.confirmLoading}
                                onClick={this.updateplanHandleClick.bind(this, this.state.updaterecord)}
                                >提交</Button>
                        ]}
                    >

                        <UpdateDingshiPlanForm ref="updateDingshiPlanForm" record={this.state.updaterecord} />

                        {
                            this.state.alertVisible ?
                                (
                                    <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                                ) : null
                        }
                    </Modal>
                <Table
                    dataSource={this.state.columnData}
                    columns={userColumns}
                    pagination={false}
                    //loading={this.state.tableLoading}
                    locale={{ emptyText: '暂无数据' }}
                    //onChange={this.handleChange}
                    //rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                    // pagination={{  //分页
                    //     defaultPageSize: 10, //默认显示几条一页
                    //     //pageSize: 10,
                    //     showTotal: function (total) {  //设置显示一共几条数据
                    //         return '共 ' + total + ' 条数据';
                    //     },
                    //     showSizeChanger: true,
                    //     showQuickJumper: true,
                    //     pageSizeOptions: [5, 10, 20, 30]
                    // }} 
                    // expandedRowRender={(record) => {    
                    //     return (
                    //         <GridInnerTable
                    //             onRef={this.onRef}
                    //             gridId={record.id}
                    //             that={this} />)
                    // }}
                    />
            </div>
        )
    }
}
class updateXunchaPlanForm extends Component{
    constructor(props) {
        super(props);
        this.state = {
            theme: props.record.theme|| [],
            startTime: props.record.startTime|| [],
            endTime: props.record.endTime|| [],
            plantimes: props.record.plantimes|| [],
        };
    }

    componentWillReceiveProps(props) {
        this.setState({
            theme: props.record.theme,
             startTime: props.record.startTime,
            endTime: props.record.endTime,
            plantimes: props.record.plantimes|| [],
        });
    }

    componentDidMount() {
        // console.log("sss", this.state.theme)
        // console.log("ssd", this.state.startTime)
    }

    render() {
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: { span: 4 },
            wrapperCol: { span: 16 },
        };

        return (
            <Form>
                <FormItem
                    label='主题'
                    {...formItemLayout}>
                    {getFieldDecorator("theme", {
                        initialValue: this.state.theme,
                        rules: [{
                            required: true,
                            message: '请输入主题！',
                        }]
                    })(
                        <Input
                            size="large"
                            prefix={
                                <Icon type="idcard" style={{ color: "rgba(0,0,0,.25)" }} />
                            }
                            placeholder="请输入主题"
                        />
                    )}
                </FormItem>
                <FormItem
                    label='开始时间'
                    {...formItemLayout}>
                    {getFieldDecorator("starttime", {
                        initialValue: moment(this.state.startTime, 'YYYY-MM-DD'),
                        rules: [{
                            required: true,
                            message: '请输入开始时间！',
                        }]
                    })(
                       <DatePicker
                            size="large"
                            prefix={
                                <Icon type="idcard" style={{ color: "rgba(0,0,0,.25)" }} />
                            }
                            placeholder="请输入开始时间"
                        />
                    )}
                </FormItem>
                <FormItem
                    label='结束时间'
                    {...formItemLayout}>
                    {getFieldDecorator("endtime", {
                        initialValue: moment(this.state.endTime, 'YYYY-MM-DD'),
                        rules: [{
                            required: true,
                            message: '请输入结束时间！',
                        }]
                    })(
                       <DatePicker
                            size="large"
                            prefix={
                                <Icon type="idcard" style={{ color: "rgba(0,0,0,.25)" }} />
                            }
                            placeholder="请输入结束时间"
                        />
                    )}
                </FormItem>
                <FormItem
                    label='计划次数'
                    {...formItemLayout}>
                    {getFieldDecorator("plantimes", {
                        initialValue: this.state.plantimes,
                        rules: [{
                            required: true,
                            message: '请输入计划次数！',
                        }]
                    })(
                        <Input
                            size="large"
                            prefix={
                                <Icon type="idcard" style={{ color: "rgba(0,0,0,.25)" }} />
                            }
                            placeholder="请输入计划次数"
                        />
                    )}
                </FormItem>
            </Form>
        );
    }
}
const UpdateXunchaPlanForm = Form.create()(updateXunchaPlanForm);
class isUsePlanForm extends Component{
    constructor(props) {
        super(props);
        this.state = {
            test:"",
            departmentId:0,
            department:[],
            isUseRecord:props.record|| []
        };
    }

    componentWillReceiveProps(props) {
        this.setState({
            isUseRecord:props.record|| []
            
        });
    }

    componentDidMount() {
         console.log("sss", this.state.isUseRecord)
        // console.log("ssd", this.state.startTime)
        this.refreshData();
        
    }
    refreshData(){
        let department=[];
        getAllChildDepartmentApi(parseInt(sessionStorage.getItem("departmentId")))
        .then((res)=>{
            res.data.forEach((item, index)=>{
                department.push({
                    departmentId:item.id,
                    departmentName:item.name,
                    parent:item.parent
                });
            });
            this.setState({
                department:department
            })
        })
    }
    onSelect=(value)=>{
        console.log("test", value);
    }

    render() {
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: { span: 4 },
            wrapperCol: { span: 16 },
        };
        const departmentOptions = this.state.department.map((d, index) =>
        <Option value={d.departmentId} key={index}>{d.departmentName}</Option>);
        return (
            <Form>
               <FormItem
                    label='分配区县'
                    {...formItemLayout}>
                    {getFieldDecorator("department", {
                        rules: [{
                            required: true,
                            message: '区县不能为空！',
                        }]
                    })(
                        <Select
                            mode="multiple"
                            disabled={this.state.departmentId}
                            size="large"
                            onChange={this.onSelect}
                            placeholder="选择区县"
                            showSearch
                            optionFilterProp="children"
                            filterOption={(input, option) =>{
                            console.log(input, option)
                             return  option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                    }}
                                    >
                             {departmentOptions}
                        </Select>
                    )}
                </FormItem>
                
            </Form>
        );
    }
}
const IsUsePlanForm = Form.create()(isUsePlanForm);
class addXunchaPlanForm extends Component{
    constructor(props) {
        super(props);
        this.state = {
           test:"",
           themeTypeInfo:[],
           themedingqi:0,
           DingqiTypeInfo:[],
           departmentId:undefined
        };
    }

    componentWillReceiveProps(props) {
       
    }

    componentDidMount() {
        // console.log("sss", this.state.theme)
        // console.log("ssd", this.state.startTime)
        this.refreshData();
    }
    refreshData(){
        let themeType=[];
        themeType.push({
            id:0,
            name:'专项巡查'
        });
        themeType.push({
            id:1,
            name:'定期巡查'
        });
        this.setState({
            themeTypeInfo:themeType
        })
        let DingqiType=[];
        DingqiType.push({
            id:0,
            name:'每月'
        });
        DingqiType.push({
            id:1,
            name:'季度'
        });
        DingqiType.push({
            id:2,
            name:'半年'
        });
        this.setState({
            DingqiTypeInfo:DingqiType
        })
        getDepartmentParentApi(parseInt(sessionStorage.getItem("departmentId")))
        .then((res)=>{
            console.log("rs", res.data)
            this.setState({
                departmentId:res.data
            })
        })
    }
    onChange = (value) => {
        console.log("test", value);
        this.setState({
            themedingqi:value-1
        })
    }
     disabledDate(current) {
        // Can not select days before today and today
        return current < moment().startOf('day');
      }
    render() {
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: { span: 4 },
            wrapperCol: { span: 16 },
        };
        const themTypeoption = this.state.themeTypeInfo.map((d, index) => <Option value={d.id+1} key={index}>{d.name}</Option>); 
        const DingqiTypeoption = this.state.DingqiTypeInfo.map((d, index) => <Option value={d.name} key={index}>{d.name}</Option>);
        return (
            <Form>
                <FormItem
                    label='主题'
                    {...formItemLayout}>
                    {getFieldDecorator("theme", {
                        rules: [{
                            required: true,
                            message: '请输入主题！',
                        }]
                    })(
                        <Input
                            size="large"
                            prefix={
                                <Icon type="idcard" style={{ color: "rgba(0,0,0,.25)" }} />
                            }
                            placeholder="请输入主题"
                        />
                    )}
                </FormItem>
                <FormItem
                    label='主题类型'
                    {...formItemLayout}>
                    {getFieldDecorator("themeType", {
                        rules: [{
                            required: true,
                            message: '主题类型不能为空！',
                        }]
                    })(
                        <Select
                            
                            size="large"
                            onSelect={this.onChange}
                            placeholder="选择主题类型">
                            {themTypeoption}
                        </Select>
                    )}
                </FormItem>
                <FormItem
                    label='定期类型'
                    {...formItemLayout}>
                    {getFieldDecorator("DingqiType", {
                        rules: [{
                            required: this.state.themedingqi,
                            message: '定期类型不能为空！',
                        }]
                    })(
                        <Select
                          
                            disabled={!this.state.themedingqi}
                            size="large"
                            placeholder="选择定期类型">
                            {DingqiTypeoption}
                        </Select>
                    )}
                </FormItem>
                <FormItem
                    label='巡查次数'
                    {...formItemLayout}>
                    {getFieldDecorator("plantimes", {
                        
                        rules: [{
                            required: true,
                            pattern: new RegExp(/^[1-9]\d*$/, "g"),
                            message: '请输入大于0的整数！',
                        }]
                    })(
                        <Input
                            size="large"
                            prefix={
                                <Icon type="idcard" style={{ color: "rgba(0,0,0,.25)" }} />
                            }
                            placeholder="请输入计划次数"
                        />
                    )}
                </FormItem>
                
                <FormItem
                    label='开始时间'
                    {...formItemLayout}>
                    {getFieldDecorator("starttime", {
                        //initialValue: moment("2021/12/12", 'YYYY-MM-DD'),
                        rules: [{
                            required: true,
                            message: '请输入开始时间！',
                        }]
                    })(
                       <DatePicker
                            size="large"
                            disabledDate={this.disabledDate}
                            prefix={
                                <Icon type="idcard" style={{ color: "rgba(0,0,0,.25)" }} />
                            }
                            placeholder="请输入开始时间"
                        />
                    )}
                </FormItem>
                <FormItem
                    label='结束时间'
                    {...formItemLayout}>
                    {getFieldDecorator("endtime", {
                        //initialValue: moment("2021/12/12", 'YYYY-MM-DD'),
                        rules: [{
                            required: true,
                            message: '请输入结束时间！',
                        }]
                    })(
                       <DatePicker
                            size="large"
                            disabledDate={this.disabledDate}
                            prefix={
                                <Icon type="idcard" style={{ color: "rgba(0,0,0,.25)" }} />
                            }
                            placeholder="请输入结束时间"
                        />
                    )}
                </FormItem>
                
            </Form>
        );
    }
}
const AddXunchaPlanForm = Form.create()(addXunchaPlanForm);
class updateDingshiPlanForm extends Component{
    constructor(props) {
        super(props);
        this.state = {
            theme: props.record.theme|| [],
            startTime: props.record.startTime|| [],
            endTime: props.record.endTime|| [],
        };
    }

    componentWillReceiveProps(props) {
        this.setState({
            theme: props.record.theme,
             startTime: props.record.startTime,
            endTime: props.record.endTime,
        });
    }

    componentDidMount() {
        // console.log("sss", this.state.theme)
        // console.log("ssd", this.state.startTime)
    }
    

    render() {
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: { span: 4 },
            wrapperCol: { span: 16 },
        };

        return (
            <Form>
                <FormItem
                    label='主题'
                    {...formItemLayout}>
                    {getFieldDecorator("theme", {
                        initialValue: this.state.theme,
                        rules: [{
                            required: true,
                            message: '请输入主题！',
                        }]
                    })(
                        <Input
                            size="large"
                            prefix={
                                <Icon type="idcard" style={{ color: "rgba(0,0,0,.25)" }} />
                            }
                            placeholder="请输入主题"
                        />
                    )}
                </FormItem>
                {/* <FormItem
                    label='开始时间'
                    {...formItemLayout}>
                    {getFieldDecorator("starttime", {
                        initialValue: moment(this.state.startTime, 'YYYY-MM-DD'),
                        rules: [{
                            required: true,
                            message: '请输入开始时间！',
                        }]
                    })(
                       <DatePicker
                            size="large"
                            prefix={
                                <Icon type="idcard" style={{ color: "rgba(0,0,0,.25)" }} />
                            }
                            placeholder="请输入开始时间"
                        />
                    )}
                </FormItem>
                <FormItem
                    label='结束时间'
                    {...formItemLayout}>
                    {getFieldDecorator("endtime", {
                        initialValue: moment(this.state.endTime, 'YYYY-MM-DD'),
                        rules: [{
                            required: true,
                            message: '请输入结束时间！',
                        }]
                    })(
                       <DatePicker
                            size="large"
                            prefix={
                                <Icon type="idcard" style={{ color: "rgba(0,0,0,.25)" }} />
                            }
                            placeholder="请输入结束时间"
                        />
                    )}
                </FormItem> */}
            </Form>
        );
    }
}
const UpdateDingshiPlanForm = Form.create()(updateDingshiPlanForm);
export {
    EduInspectNum, EduInspectFinishedRate, EduInspectCompositeRank, EduPatrolNumRank, EduPatrolRatesRank, EduPatrolPointsRank,
    EduDangerNumRank, EduDangerCategory, EduDangerDealRateRank, ComprehensivePointsRank, xunchaPlan, XunchaRecord, DailyRecord
};
